GetOverContent() public method

public GetOverContent ( int pageNum ) : PdfContentByte
pageNum int
return PdfContentByte
 /// <summary>
 /// Fills out and flattens a form with the name, company and country.
 /// </summary>
 /// <param name="src"> the path to the original form </param>
 /// <param name="dest"> the path to the filled out form </param>
 public void ManipulatePdf(String src, String dest)
 {
     PdfReader reader = new PdfReader(src);
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
     int n = reader.NumberOfPages;
     Rectangle pagesize;
     for (int i = 1; i <= n; i++)
     {
         PdfContentByte over = stamper.GetOverContent(i);
         pagesize = reader.GetPageSize(i);
         float x = (pagesize.Left + pagesize.Right) / 2;
         float y = (pagesize.Bottom + pagesize.Top) / 2;
         PdfGState gs = new PdfGState();
         gs.FillOpacity = 0.3f;
         over.SaveState();
         over.SetGState(gs);
         over.SetRGBColorFill(200, 200, 0);
         ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER,
             new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
             x, y, 45);
         over.RestoreState();
     }
     stamper.Close();
     reader.Close();
 }
 // ---------------------------------------------------------------------------    
 /**
  * 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();
     }
 }
        public void Go()
        {
            using (PdfReader reader = new PdfReader(GetTestReader()))
            {
                var outputFile = Helpers.IO.GetClassOutputPath(this);

                using (var stream = new FileStream(outputFile, FileMode.Create))
                {
                    using (PdfStamper stamper = new PdfStamper(reader, stream))
                    {
                        AcroFields form = stamper.AcroFields;
                        var fldPosition = form.GetFieldPositions(NAME)[0];
                        Rectangle rectangle = fldPosition.position;
                        string base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
                        Regex regex = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)");
                        Match match = regex.Match(base64Image);
                        Image image = Image.GetInstance(
                            Convert.FromBase64String(match.Groups["data"].Value)
                        );
                        // best fit if image bigger than form field
                        if (image.Height > rectangle.Height || image.Width > rectangle.Width)
                        {
                            image.ScaleAbsolute(rectangle);
                        }
                        // form field top left - change parameters as needed to set different position 
                        image.SetAbsolutePosition(rectangle.Left + 2, rectangle.Top - 8);
                        stamper.GetOverContent(fldPosition.page).AddImage(image);
                    }
                }
            }
        }
Example #4
0
        public static void PDFStamp(string inputPath, string outputPath, string watermarkPath)
        {
            try
            {
                PdfReader pdfReader = new PdfReader(inputPath);
                int numberOfPages = pdfReader.NumberOfPages;
                FileStream outputStream = new FileStream(outputPath, FileMode.Create);

                PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
                PdfContentByte waterMarkContent;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;

                float height = psize.Height;

                string watermarkimagepath = watermarkPath;
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkimagepath);
                image.ScalePercent(70f);
                image.SetAbsolutePosition(width / 10, height / 9);

                /*                        image.ScaleAbsoluteHeight(10);
                                        image.ScaleAbsoluteW idth(10);*/

                //   waterMarkContent = pdfStamper.GetUnderContent(1);
                // waterMarkContent.AddImage(image);

                for (int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印

                    waterMarkContent.AddImage(image);
                }

                pdfStamper.Close();
                pdfReader.Close();
                System.IO.File.Move(outputPath, inputPath);
            }
            catch (Exception)
            {

            }
              /*  finally
            {

                pdfStamper.Close();
                pdfReader.Close();
            }*/

            /*            System.IO.File.Delete(inputPath);

                        System.IO.File.Move(outputPath, inputPath);
                         System.IO.File.Delete(outputPath);*/
        }
Example #5
0
// ---------------------------------------------------------------------------
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param resource the original PDF
     */
    public static byte[] Stamp(byte[] resource) {
      PdfReader reader = new PdfReader(resource);
      using (var ms = new MemoryStream()) {
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          PdfContentByte canvas = stamper.GetOverContent(1);
          ColumnText.ShowTextAligned(
            canvas,
            Element.ALIGN_LEFT, 
            new Phrase("Hello people!"), 
            36, 540, 0
          );
        }
        return ms.ToArray();
      }
    }
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
        {
            // image file extension check ignore for brevity
            var fileList = files.Where(h => h != null && h.ContentLength > 0);
            if (fileList.Count() < 1)
                throw new Exception("no files uploaded");

            var absoluteX = 20;
            var absoluteY = 800;
            using (var stream = new MemoryStream())
            {
                using (var stamper = new PdfStamper(Helpers.Pdf.GetTestReader(), stream))
                {
                    var pageOneSize = stamper.Reader
                        .GetPageSize(APPEND_NEW_PAGE_NUMBER - 1);
                    foreach (var file in fileList)
                    {
                        using (var br = new BinaryReader(file.InputStream))
                        {
                            var imageBytes = br.ReadBytes(file.ContentLength);
                            var image = Image.GetInstance(imageBytes);

                            // still not sure if you want to add a new blank page, but 
                            // here's how
                            stamper.InsertPage(
                                APPEND_NEW_PAGE_NUMBER,
                                pageOneSize
                            );

                            // image absolute position
                            image.SetAbsolutePosition(
                                absoluteX, absoluteY - image.Height
                            );

                            // scale image if needed
                            // image.ScaleAbsolute(...);

                            // PAGE_NUMBER => add image to specific page number
                            stamper.GetOverContent(APPEND_NEW_PAGE_NUMBER)
                                .AddImage(image);
                        }
                        ++APPEND_NEW_PAGE_NUMBER;
                    }
                }
                return File(stream.ToArray(), "application/pdf", "test.pdf");
            }
        }
Example #7
0
        private static InsertResult InsertImpl(IInput context, Stream input, int page, PdfImage image, PointF imageOffset, PdfImageStyle style)
        {
            var outputStream = new MemoryStream();

            try
            {
                var reader  = new TextSharp.PdfReader(input);
                var stamper = new TextSharp.PdfStamper(reader, outputStream);

                var pages = reader.NumberOfPages;
                for (var pdfPage = 1; pdfPage <= pages; pdfPage++)
                {
                    if (pdfPage != page)
                    {
                        continue;
                    }

                    var cb = stamper.GetOverContent(pdfPage);
                    image.Image.SetAbsolutePosition(imageOffset.X, imageOffset.Y);
                    cb.AddImage(image.Image);
                    break;
                }

                stamper.Close();
                reader.Close();

                return(InsertResult.CreateSuccessResult(new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = new MemoryStream(outputStream.GetBuffer())
                }));
            }
            catch (Exception ex)
            {
                return(InsertResult.FromException(
                           ex,
                           new InsertResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Example #8
0
 public void ManipulatePdf(string src, string dest)
 {
     PdfReader reader = new PdfReader(src);
     // We assume that there's a single large picture on the first page
     PdfDictionary page = reader.GetPageN(1);
     PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);
     PdfDictionary xobjects = resources.GetAsDict(PdfName.XOBJECT);
     Dictionary<PdfName, PdfObject>.KeyCollection.Enumerator enumerator = xobjects.Keys.GetEnumerator();
     enumerator.MoveNext();
     PdfName imgName = enumerator.Current;
     Image img = Image.GetInstance((PRIndirectReference) xobjects.GetAsIndirectObject(imgName));
     img.SetAbsolutePosition(0, 0);
     img.ScaleAbsolute(reader.GetPageSize(1));
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest,FileMode.Create));
     stamper.GetOverContent(1).AddImage(img);
     stamper.Close();
     reader.Close();
 }
 /// <summary>
 /// Accepts a list of MyItem objects and draws a colored rectangle for each
 /// item in the list.
 /// </summary>
 /// <param name="items">The list of items</param>
 /// <param name="reader">The reader instance that has access to the PDF file</param>
 /// <param name="pageNum">The page number of the page that needs to be parsed</param>
 /// <param name="destination">The path for the altered PDF file</param>
 public void Highlight(List<MyItem> items, PdfReader reader, int pageNum, String destination)
 {
     PdfStamper stamper = new PdfStamper(reader, new FileStream(destination, FileMode.Create));
     PdfContentByte over = stamper.GetOverContent(pageNum);
     foreach (MyItem item in items)
     {
         if (item.Color == null)
             continue;
         over.SaveState();
         over.SetColorStroke(item.Color);
         over.SetLineWidth(2);
         Rectangle r = item.Rectangle;
         over.Rectangle(r.Left, r.Bottom, r.Width, r.Height);
         over.Stroke();
         over.RestoreState();
     }
     stamper.Close();
 }
 // ---------------------------------------------------------------------------
 /**
  * Manipulates a PDF file src with the file dest as result (localhost)
  * @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))
         {
             // Add JavaScript
             jsString = File.ReadAllText(
               Path.Combine(Utility.ResourceJavaScript, RESOURCE)
             );
             stamper.JavaScript = jsString;
             // Create a Chunk with a chained action
             PdfContentByte canvas;
             Chunk chunk = new Chunk("print this page");
             PdfAction action = PdfAction.JavaScript(
               "app.alert('Think before you print!');",
               stamper.Writer
             );
             action.Next(PdfAction.JavaScript(
               "printCurrentPage(this.pageNum);",
               stamper.Writer
             ));
             action.Next(new PdfAction("http://www.panda.org/savepaper/"));
             chunk.SetAction(action);
             Phrase phrase = new Phrase(chunk);
             // Add this Chunk to every page
             for (int i = 0; i < n; )
             {
                 canvas = stamper.GetOverContent(++i);
                 ColumnText.ShowTextAligned(
                   canvas, Element.ALIGN_RIGHT, phrase, 816, 18, 0
                 );
             }
         }
         return ms.ToArray();
     }
 }
        private void ParseAndHighlight(String input, String output, bool singleCharacters) {
            PdfReader reader = new PdfReader(input);
            FileStream fos = new FileStream(output, FileMode.Create);
            PdfStamper stamper = new PdfStamper(reader, fos);

            PdfReaderContentParser parser = new PdfReaderContentParser(reader);
            MyRenderListener myRenderListener = singleCharacters ? new MyCharacterRenderListener() : new MyRenderListener();
            for (int pageNum = 1; pageNum <= reader.NumberOfPages; pageNum++) {
                List<Rectangle> rectangles = parser.ProcessContent(pageNum, myRenderListener).GetRectangles();
                PdfContentByte canvas = stamper.GetOverContent(pageNum);
                canvas.SetLineWidth(0.5f);
                canvas.SetColorStroke(BaseColor.RED);
                foreach (Rectangle rectangle in rectangles) {
                    canvas.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                    canvas.Stroke();
                }
            }
            stamper.Close();
            fos.Close();
            reader.Close();
        }
Example #12
0
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        zip.AddFile(PREFACE, "");
        PdfReader reader = new PdfReader(PREFACE);
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        using (MemoryStream ms = new MemoryStream()) {
          using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            TextMarginFinder finder;
            for (int i = 1; i <= reader.NumberOfPages; i++) {
              finder = parser.ProcessContent(i, new TextMarginFinder());
              PdfContentByte cb = stamper.GetOverContent(i);
              cb.Rectangle(
                finder.GetLlx(), finder.GetLly(),
                finder.GetWidth(), finder.GetHeight()
              );
              cb.Stroke();
            }
          }
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.Save(stream);             
      }
    }
Example #13
0
        public MemoryStream CreateCompanyRegistrationDocument(string fileName, string companyName, string companyNumber)
        {
            using (var stumpedDocStream = new MemoryStream())
            {
                PdfReader reader = null;
                PdfStamper stamper = null;
                try
                {
                    reader = new PdfReader(fileName);
                    stamper = new PdfStamper(reader, stumpedDocStream);
                    var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    var font = new Font(bf, textSize);
                    for (var pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
                    {
                        var canvas = stamper.GetOverContent(pageNumber);
                        canvas.SetFontAndSize(bf, textSize);
                        RenderPhase(pageNumber, companyNameLocations, canvas, companyName, font);
                        RenderPhase(pageNumber, companyNumberLocations, canvas, companyNumber, font);
                    }
                }
                finally
                {
                    try
                    {
                        if(reader!=null)
                            reader.Close();
                    }
                    finally
                    {
                        if (stamper != null)
                            stamper.Close();
                    }
                }

                return new MemoryStream(EncryptPdf(stumpedDocStream.ToArray()));
            }
        }
Example #14
0
        public bool AddContent(string filePath, string date, string originalNum, string bhNum, string weightLb, string weightKg, string senderName, string senderAddress, string senderPhone, string receiverName, string receiveAddress, string receiverZip, string receiverPhone, string goodsName, string goodsPrice, ref string referror)
        {
            Document document = new Document();
            try {
                string fileName = null;
                DirectoryInfo dr = new DirectoryInfo(filePath);
                if (!dr.Exists) {
                    dr.Create();
                }
                fileName = filePath + "\\" + bhNum + ".pdf";
                string applicationPath = System.Web.HttpContext.Current.Server.MapPath("\\");
                PdfReader pdfReader = new PdfReader(applicationPath + "\\Assist\\pdfData\\pdftemplate.pdf");
                PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(fileName, FileMode.Create));
                //四种字体
                BaseFont chFont = BaseFont.CreateFont("c:\\windows\\fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFont barCodeFont = BaseFont.CreateFont(applicationPath + "\\Assist\\pdfData\\HC39M.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFont blackFont = BaseFont.CreateFont(applicationPath + "\\Assist\\pdfData\\calibrib.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                PdfContentByte over = pdfStamper.GetOverContent(1);

                over.BeginText();

                over.SetFontAndSize(blackFont, 10);  //英文黑粗
                //日期
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, date, 90, 719, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, date, 90, 362, 0);
                //编号
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, bhNum, 298, 734, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, bhNum, 298, 378, 0);
                //发货人姓名
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderName, 90, 691, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderName, 90, 334, 0);
                //发货人地址
                if (senderAddress.Length > 40) {
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress.Substring(0, 40), 88, 676, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress.Substring(40), 88, 662, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress.Substring(0, 40), 88, 320, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress.Substring(40), 88, 306, 0);
                }
                else {
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress, 88, 676, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderAddress, 88, 320, 0);
                }
                //收货人电话
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverPhone, 458, 691, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverPhone, 458, 334, 0);
                //收货人邮编
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverZip, 466, 634, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverZip, 466, 277, 0);
                //价格
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, goodsPrice, 109, 531, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, goodsPrice, 109, 174, 0);
                //发货人电话
                over.SetFontAndSize(blackFont, 8);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderPhone, 220, 691, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, senderPhone, 220, 334, 0);
                //货物重量
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, weightKg, 87, 588, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, weightKg, 87, 233, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, weightLb, 87, 579, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, weightLb, 87, 223, 0);
                //条形码
                over.SetFontAndSize(barCodeFont, 12);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "*" + bhNum + "*", 390, 739, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "*" + bhNum + "*", 390, 384, 0);
                //备注
                over.SetFontAndSize(chFont, 8);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, originalNum, 476, 439, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, originalNum, 476, 82, 0);
                //收件人姓名
                over.SetFontAndSize(chFont, 11);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverName, 343, 691, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiverName, 343, 335, 0);
                //收件人地址
                int chNum = 40;
                if (IsChineseLetter(receiveAddress, 0) && IsChineseLetter(receiveAddress, 1)) {
                    chNum = 20;
                }
                if (receiveAddress.Length > chNum) {
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress.Substring(0, chNum), 344, 676, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress.Substring(chNum), 344, 663, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress.Substring(0, chNum), 344, 320, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress.Substring(chNum), 344, 306, 0);
                }
                else {
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress, 344, 676, 0);
                    over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, receiveAddress, 344, 320, 0);
                }
                //名称
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, goodsName, 43, 600, 0);
                over.ShowTextAligned(PdfContentByte.ALIGN_LEFT, goodsName, 43, 243, 0);

                over.EndText();
                pdfStamper.Close();
                return true;
            }
            catch (Exception ex) {
                referror += ex.Message.ToString();
                return false;
            }
            finally {
                document.Close();
            }
        }
Example #15
0
        // ---------------------------------------------------------------------------
        /**
         * Manipulates a PDF file src
         * @param src the original PDF
         * @param stationery the resulting PDF
         */
        public byte[] ManipulatePdf(byte[] src, byte[] stationery)
        {
            ColumnText ct = new ColumnText(null);
            string SQL =
      @"SELECT country, id FROM film_country 
ORDER BY country
";
            using (var c = AdoDB.Provider.CreateConnection())
            {
                c.ConnectionString = AdoDB.CS;
                using (DbCommand cmd = c.CreateCommand())
                {
                    cmd.CommandText = SQL;
                    c.Open();
                    using (var r = cmd.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            ct.AddElement(new Paragraph(
                              24, new Chunk(r["country"].ToString())
                            ));
                        }
                    }
                }
            }
            // Create a reader for the original document and for the stationery
            PdfReader reader = new PdfReader(src);
            PdfReader rStationery = new PdfReader(stationery);
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create an imported page for the stationery
                    PdfImportedPage page = stamper.GetImportedPage(rStationery, 1);
                    int i = 0;
                    // Add the content of the ColumnText object 
                    while (true)
                    {
                        // Add a new page
                        stamper.InsertPage(++i, reader.GetPageSize(1));
                        // Add the stationary to the new page
                        stamper.GetUnderContent(i).AddTemplate(page, 0, 0);
                        // Add as much content of the column as possible
                        ct.Canvas = stamper.GetOverContent(i);
                        ct.SetSimpleColumn(36, 36, 559, 770);
                        if (!ColumnText.HasMoreText(ct.Go()))
                            break;
                    }
                }
                return ms.ToArray();
            }
        }
Example #16
0
        public AsistenciaLegal(AufenPortalReportesDataContext db, EMPRESA empresa, vw_Ubicacione departamento, DateTime FechaDesde, DateTime FechaHasta, string path, string rut)
        {
            // Vamos a buscar los datos que nos permitirtán armar elreporte
            NombreArchivo = String.Format("{0}/{1}/LibroAtrasos.pdf", empresa.Descripcion, departamento.Descripcion);
            //Resultado de marcas
             IEnumerable<sp_LibroAsistenciaResult> resultadoLibroAtrasos =
                                           db.sp_LibroAsistencia(
                                           FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           int.Parse(empresa.Codigo).ToString(),
                                           departamento.Codigo,
                                           rut).ToList();
             IEnumerable<LibroAsistenciaDTO> resultado = Mapper.Map<IEnumerable<sp_LibroAsistenciaResult>,
             IEnumerable<LibroAsistenciaDTO>>(resultadoLibroAtrasos);
            // Resumen de inasistencias
             IEnumerable<sp_LibroInasistenciaResult> resultadoLibroInasistencias =
                 db.sp_LibroInasistencia(FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
                    , FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
                    , int.Parse(empresa.Codigo).ToString()
                    , departamento.Codigo
                    , rut);

            IEnumerable<LibroInasistenciaDTO> resultadoInasistencia = Mapper.Map<IEnumerable<sp_LibroInasistenciaResult>,
                 IEnumerable<LibroInasistenciaDTO>>(resultadoLibroInasistencias);
             if (resultadoLibroAtrasos.Any())
             {
                 string[] diasSemana = new[] { "dom", "lun", "mar", "mie", "ju", "vie", "sab" };
                 using (MemoryStream finalStream = new MemoryStream())
                 {
                     PdfCopyFields copy = new PdfCopyFields(finalStream);
                     foreach (var reporte in resultado.Where(x => x.Rut != null).GroupBy(x => new
                     {
                         x.Rut,
                         x.IdEmpresa,
                         x.IdDepartamento,
                         Mes = x.Fecha.Value.Month,
                         Anio = x.Fecha.Value.Year
                     }))
                     {
                         var inasistencias = resultadoInasistencia.Where(x => x.Rut!= null &&
                             x.Rut == reporte.Key.Rut &&
                             x.IdEmpresa == reporte.Key.IdEmpresa &&
                             x.IdDepartamento == reporte.Key.IdDepartamento &&
                            reporte.Key.Mes == x.Fecha.Value.Month &&
                            reporte.Key.Anio == x.Fecha.Value.Year);
                         var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo &&
                             x.IdUbicacion == reporte.Key.IdDepartamento &&
                                  x.Codigo == reporte.Key.Rut);
                         int numeroSemanas = reporte.Max(x => x.NumSemana) == 6 ? 6 : 5;
                         using (MemoryStream ms = new MemoryStream())
                         {
                             using (PdfReader pdfReader = new PdfReader(path + String.Format(@"\ReporteAsistenciaLegal{0}.pdf",  numeroSemanas)))
                             {
                                 DateTime fechaReferencia = reporte.First().Fecha.Value;
                                 DateTime primerDiaMes = new DateTime(fechaReferencia.Year, fechaReferencia.Month, 1);
                                 DateTime ultimoDiaMes = primerDiaMes.AddMonths(1).AddSeconds(-1);
                                 PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

                                 int PageCount = pdfReader.NumberOfPages;
                                 for (int x = 1; x <= PageCount; x++)
                                 {
                                     PdfContentByte cb = pdfStamper.GetOverContent(x);
                                     Image imagen = Image.GetInstance(String.Format(@"{0}\imagenes\LogosEmpresas\logo{1}.jpg", path, empresa.Codigo.Trim()));
                                     imagen.ScaleToFit(100, 200);
                                     imagen.SetAbsolutePosition(450, 750);
                                     cb.AddImage(imagen);
                                 }

                                 pdfStamper.AcroFields.SetField("Mes", new DateTime(reporte.Key.Anio, reporte.Key.Mes, 1).ToString("yyyy MMM"));
                                 pdfStamper.AcroFields.SetField("Nombre", empleado != null ? empleado.NombreCompleto : String.Empty);
                                 pdfStamper.AcroFields.SetField("Rut", empleado.RutAufen);
                                 pdfStamper.AcroFields.SetField("Departamento", String.Format("{0} ({1})", departamento!= null ? departamento.SucursalPlanta : String.Empty, empresa!=null ? empresa.Descripcion.Trim() : String.Empty));
                                 pdfStamper.AcroFields.SetField("Fecha", String.Format("{0} - {1}", primerDiaMes.ToShortDateString(), ultimoDiaMes.ToShortDateString()));
                                 pdfStamper.AcroFields.SetField("ImpresoPagina1", DateTime.Now.ToShortDateString());
                                 pdfStamper.AcroFields.SetField("ImpresoPagina2", DateTime.Now.ToShortDateString());
                                 pdfStamper.AcroFields.SetField("UsuarioPagina1", "");
                                 pdfStamper.AcroFields.SetField("UsuarioPagina2", "");
                                 //Para todas las semanas
                                 for (int i = 1; i <=  numeroSemanas; i++)
                                 {
                                     //Para todos los días de la semana
                                     var semana = reporte.Where(x => x.NumSemana == i);
                                     for (int j = 0; j <= 6; j++)
                                     {
                                        // Si se elimina esto el domingo va aquedar al final
                                        int correccionDia = j;//j == 6 ? 0 : j + 1;
                                         var dia = reporte.FirstOrDefault(x => x.NumSemana == i && (int)x.Fecha.Value.DayOfWeek == j);
                                         //
                                         pdfStamper.AcroFields.SetField(String.Format("Semana{0}Tipo{1}", i, correccionDia),
                                             String.Format("{0}\n{1}",
                                                String.Format("{0}-{1}", dia!= null && dia.Entrada.HasValue ? dia.Entrada.Value.ToString("HH:mm") : String.Empty
                                                    , dia!=null && dia.Salida.HasValue ? dia.Salida.Value.ToString("HH:mm") : String.Empty),
                                                dia != null ? dia.Observacion : String.Empty));
                                        pdfStamper.AcroFields.SetField(String.Format("Semana{0}Dia{1}", i, correccionDia), String.Format("{0} {1}", dia != null ? dia.Fecha.Value.ToString("dd/MM") : string.Empty, diasSemana[j]));
                                     }
                                     // Semana a semana
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}Jornada", i), semana.CalculaJornada());
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}Asistencia", i), semana.CalculaAsistencia());

                                     //  T. de Salida = inasistencia justifica
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}Salidas", i), semana.CalculaInasistenciaJustificadaLegal());

                                     //  T. de Ausencia = inasistencia INjustificada
                                     //var inasistenciaSemanal = inasistencias.Where(x => x.Fecha.HasValue && x.Fecha.Value.Day >= (i - 1) * 7 && x.Fecha.Value.Day <= i * 7);
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}Ausencias", i), semana.CalculaInasistenciaInjustificadaLegal());
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}AtrasosSalidas", i), semana.CalculaAtrasoSalida());
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}NumeroAtrasos", i), semana.CalculaDiasAtraso());
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}NumeroSalidas", i), semana.CalculaDiasSalidaAdelantada());
                                     pdfStamper.AcroFields.SetField(String.Format("Semana{0}ExtraConTurno", i), semana.CalculaHorasExtra());
                                     //pdfStamper.AcroFields.SetField(String.Format("Semana{0}ExtraSinTurno", i), "");
                                 }
                                 // Resumen de todas las semanas
                                 pdfStamper.AcroFields.SetField("ResumenJornada", reporte.CalculaJornada());
                                 pdfStamper.AcroFields.SetField("ResumenAsistencia", reporte.CalculaAsistencia());
                                 pdfStamper.AcroFields.SetField("ResumenSalidas", reporte.CalculaInasistenciaJustificadaLegal());
                                 pdfStamper.AcroFields.SetField("ResumenAusencias", reporte.CalculaInasistenciaInjustificadaLegal());
                                 pdfStamper.AcroFields.SetField("ResumenAtrasosSalidas", reporte.CalculaAtrasoEntrada());
                                 pdfStamper.AcroFields.SetField("ResumenNumeroAtrasos", reporte.CalculaDiasAtraso());
                                 pdfStamper.AcroFields.SetField("ResumenNumeroSalidas", reporte.CalculaDiasSalidaAdelantada());
                                 pdfStamper.AcroFields.SetField("ResumenExtraConTurno", reporte.CalculaHorasExtra());
                                 //pdfStamper.AcroFields.SetField("ResumenExtraSinTurno", "");
                                 pdfStamper.Writer.CloseStream = false;
                                 pdfStamper.FormFlattening = true;
                                 pdfStamper.Close();
                                 ms.Position = 0;
                                 copy.AddDocument(new PdfReader(ms));
                                 ms.Dispose();
                             }
                         }
                     }
                     copy.Close();
                     _Archivo = finalStream.ToArray();
                 }
             }
        }
        void SignatureWasCompleted(byte[] signatureImage, string name)
        {
            NavigationController.PopViewControllerAnimated( false );

            var dirPath = Path.Combine (System.Environment.GetFolderPath (Environment.SpecialFolder.Personal), "SignedPDF");

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

            string fileName = string.Format("result-{0}.pdf", Guid.NewGuid().ToString());
            var signedFilePath = Path.Combine (dirPath, fileName);

            if (File.Exists(signedFilePath))
                File.Delete(signedFilePath);

            using (Stream inputPdfStream = new FileStream("Salesinvoice.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))              
            using (Stream outputPdfStream = new FileStream(signedFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var reader = new PdfReader(inputPdfStream);
                var stamper = new PdfStamper(reader, outputPdfStream);
                var pdfContentByte = stamper.GetOverContent(1);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(signatureImage);
                image.SetAbsolutePosition(90, 90);
                var width = 200F;
                image.ScaleToFit(width, (float)(width * (200.0 / 480.0)));
                pdfContentByte.AddImage(image);
                stamper.Close();
            }

            //Display signature after saved
            QLPreviewItemFileSystem prevItem = new QLPreviewItemFileSystem (fileName, signedFilePath);
            QLPreviewController previewController = new QLPreviewController ();
            previewController.DataSource = new PreviewControllerDS (prevItem);
            NavigationController.SetNavigationBarHidden( false, true );
            NavigationController.PushViewController (previewController, true);
        }
Example #18
0
        private void Startbtn_Click(object sender, EventArgs e)
        {
            this.Startbtn.Enabled = false;
            this.Quitbtn.Enabled = false;
            ArrayList imagelist = new ArrayList();

            object A = this.AttachFiledgv.Rows[0].Cells["StartPage"].Value;
            if (A != null)
            {
                traystart = A.ToString();
            }

            object B = this.AttachFiledgv.Rows[0].Cells["EndPage"].Value;
            if (B != null)
            {
                trayend = B.ToString();
            }

            object C = this.AttachFiledgv.Rows[1].Cells["StartPage"].Value;
            if (C != null)
            {
                partstart = C.ToString();
            }
            object D = this.AttachFiledgv.Rows[1].Cells["EndPage"].Value;
            if (D != null)
            {
                partend = D.ToString();
            }

            object E = this.AttachFiledgv.Rows[2].Cells["StartPage"].Value;
            if (E != null)
            {
                materialstart = E.ToString();
            }
            object F = this.AttachFiledgv.Rows[2].Cells["EndPage"].Value;
            if (F != null)
            {
                materialend = F.ToString();
            }

            object G = this.AttachFiledgv.Rows[3].Cells["StartPage"].Value;
            if (G != null)
            {
                weightstart = G.ToString();
            }
            object H = this.AttachFiledgv.Rows[3].Cells["EndPage"].Value;
            if (H != null)
            {
                weightend = H.ToString();
            }

            object J = this.AttachFiledgv.Rows[4].Cells["StartPage"].Value;
            if (J != null)
            {
                flangestart = J.ToString();
            }
            object K = this.AttachFiledgv.Rows[4].Cells["EndPage"].Value;
            if (K != null)
            {
                flangend = K.ToString();
            }

            DownLoadFrontPage();

            string pdfTemplate = User.rootpath + "\\" + drawing + ".pdf";
            if (string.IsNullOrEmpty(pdfTemplate))
            {
                return;
            }
            string pdfnewfile = pdfTemplate.Substring(0, pdfTemplate.LastIndexOf('.'));
            string newFile = pdfnewfile + "new.pdf";
            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            string cardstr = GetImageName();
            string[] cardno = cardstr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i <= cardno.Length - 1; i++)
            {
                string chartLoc = string.Format(@"\\ecdms\sign$\jpg\{0}.jpg", cardno[i]);
                imagelist.Add(chartLoc);
            }
            Single X = 0, Y = 43;
            if (imagelist.Count == 0)
            {
                MessageBox.Show("系统没有查询到相关电子签名,请与管理员联系");
                return;
            }
            else if(imagelist.Count == 4)
            {
                foreach (string item in imagelist)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(item);
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;

                    try
                    {
                        rect = pdfReader.GetPageSizeWithRotation(1);
                        X = 190;
                        Y += 13;
                        chartImg.ScalePercent(20);
                        chartImg.SetAbsolutePosition(X, Y);
                        underContent = pdfStamper.GetOverContent(1);
                        underContent.AddImage(chartImg);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }

            else if (imagelist.Count == 5)
            {
                for (int i = 0; i < imagelist.Count; i++)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(imagelist[i].ToString());
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;
                    rect = pdfReader.GetPageSizeWithRotation(1);
                    chartImg.ScalePercent(20);
                    if (i == 0)
                    {
                        X = 190;Y = 56;
                    }
                    else if (i == 1)
                    {
                        X = 190; Y = 69;
                    }
                    else if (i == 2)
                    {
                        X = 180; Y = 82;
                    }
                    else if (i == 3)
                    {
                        X = 205; Y = 82;
                    }
                    else if (i == 4)
                    {
                        X = 190; Y = 95;
                    }
                    chartImg.SetAbsolutePosition(X, Y);
                    underContent = pdfStamper.GetOverContent(1);
                    underContent.AddImage(chartImg);
                }
            }

            else if (imagelist.Count == 6)
            {
                for (int i = 0; i < imagelist.Count; i++)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(imagelist[i].ToString());
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;
                    rect = pdfReader.GetPageSizeWithRotation(1);
                    chartImg.ScalePercent(20);
                    if (i == 0)
                    {
                        X = 190; Y = 56;
                    }
                    else if (i == 1)
                    {
                        X = 180; Y = 69;
                    }
                    else if (i == 2)
                    {
                        X = 205; Y = 69;
                    }
                    else if (i == 3)
                    {
                        X = 180; Y = 82;
                    }
                    else if (i == 4)
                    {
                        X = 205; Y = 82;
                    }
                    else if (i == 5)
                    {
                        X = 190; Y = 95;
                    }
                    chartImg.SetAbsolutePosition(X, Y);
                    underContent = pdfStamper.GetOverContent(1);
                    underContent.AddImage(chartImg);
                }
            }

            InsertCharacteristics(pdfStamper, traystart, 340, 394);
            InsertCharacteristics(pdfStamper, trayend, 395, 394);

            InsertCharacteristics(pdfStamper, partstart, 340, 383);
            InsertCharacteristics(pdfStamper, partend, 395, 383);

            InsertCharacteristics(pdfStamper, materialstart, 340, 371);
            InsertCharacteristics(pdfStamper, materialend, 395, 371);

            InsertCharacteristics(pdfStamper, weightstart, 340, 360);
            InsertCharacteristics(pdfStamper, weightend, 395, 360);

            InsertCharacteristics(pdfStamper, flangestart, 340, 348);
            InsertCharacteristics(pdfStamper, flangend, 395, 348);

            pdfStamper.Close();
            pdfReader.Close();
            FileInfo fi = new FileInfo(pdfTemplate);
            fi.Delete();
            File.Move(newFile, pdfTemplate);

            Thread.Sleep(2000);
            string comText = "UPDATE SP_CREATEPDFDRAWING SET UPDATEDFRONTPAGE = :dfd WHERE PROJECTID = '" + projectid + "' AND DRAWINGNO = '" + drawing + "' and flag = 'Y'";
            InsertFrontPage.UpdateFrontPage(comText, User.rootpath + "\\" + drawing + ".pdf");
            FileInfo file = new FileInfo(pdfTemplate);
            file.Delete();

            this.Quitbtn.Enabled = true;
            this.Quitbtn.Text = "完成";
        }
 private void TimestampPdf()
 {
     using (var pdfReader = new PdfReader(this.PdfProcessingPath))
     {
         using (var pdfStamper = new PdfStamper(pdfReader, new FileStream(this.PdfPath, FileMode.Create)))
         {
             var parentField = PdfFormField.CreateTextField(pdfStamper.Writer, false, false, 0);
             parentField.FieldName = FieldName;
             var lineSeparator = new LineSeparator();
             for (var pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
             {
                 var pdfContentByte = pdfStamper.GetOverContent(pageNumber);
                 TextField textField = null;
                 if (this.Orientation == PdfOrientation.Portrait)
                 {
                     lineSeparator.DrawLine(pdfContentByte, PortraitFieldLeftX, PortraitFieldRightX, PortraitFieldUnderlineHeight);
                     textField = new TextField(pdfStamper.Writer, new Rectangle(PortraitFieldLeftX, PortraitFieldLeftY, PortraitFieldRightX, PortraitFieldRightY), null);
                     textField.Visibility = TextField.HIDDEN_BUT_PRINTABLE;
                 }
                 var childField = textField.GetTextField();
                 parentField.AddKid(childField);
                 childField.PlaceInPage = pageNumber;
             }
             pdfStamper.AddAnnotation(parentField, 1);
             var pdfAction = PdfAction.JavaScript(LoadTimestampScript(), pdfStamper.Writer);
             pdfStamper.Writer.SetAdditionalAction(PdfWriter.WILL_PRINT, pdfAction);
         }
     }
 }
Example #20
0
// ---------------------------------------------------------------------------
    public byte[] FillTemplate(byte[] pdf, Movie movie) {
      using (MemoryStream ms = new MemoryStream()) {
        PdfReader reader = new PdfReader(pdf);
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          AcroFields form = stamper.AcroFields;
          BaseColor color = WebColors.GetRGBColor(
            "#" + movie.entry.category.color
          );
          PushbuttonField bt = form.GetNewPushbuttonFromField(POSTER);
          bt.Layout = PushbuttonField.LAYOUT_ICON_ONLY;
          bt.ProportionalIcon = true;
          bt.Image = Image.GetInstance(Path.Combine(IMAGE, movie.Imdb + ".jpg"));
          bt.BackgroundColor = color;
          form.ReplacePushbuttonField(POSTER, bt.Field);
          
          PdfContentByte canvas = stamper.GetOverContent(1);
          float size = 12;
          AcroFields.FieldPosition f = form.GetFieldPositions(TEXT)[0];
          while (AddParagraph(CreateMovieParagraph(movie, size),
              canvas, f, true) && size > 6) 
          {
              size -= 0.2f;
          }
          AddParagraph(CreateMovieParagraph(movie, size), canvas, f, false);
          
          form.SetField(YEAR, movie.Year.ToString());
          form.SetFieldProperty(YEAR, "bgcolor", color, null);
          form.SetField(YEAR, movie.Year.ToString());
          stamper.FormFlattening = true;
        }
        return ms.ToArray();
      }
    }
Example #21
0
 public void Run() {
     try {
         PdfReader reader =
             new PdfReader(File.Open(TEST_RESOURCES_PATH + "test.pdf", FileMode.Open, FileAccess.Read,
                 FileShare.Read));
         PdfStamper stamper = new PdfStamper(reader,
             new FileStream(TARGET_PATH + "out" + threadNumber + ".pdf", FileMode.Create));
         PdfContentByte cb = stamper.GetOverContent(1);
         cb.BeginText();
         BaseFont font = BaseFont.CreateFont(TEST_RESOURCES_PATH + "FreeSans.ttf",
             threadNumber%2 == 0 ? BaseFont.IDENTITY_H : BaseFont.WINANSI, BaseFont.EMBEDDED);
         cb.SetFontAndSize(font, 12);
         cb.MoveText(30, 600);
         cb.ShowText("`1234567890-=qwertyuiop[]asdfghjkl;'\\zxcvbnm,./");
         cb.EndText();
         stamper.Close();
         reader.Close();
     }
     catch (Exception exc) {
         RegisterException(threadNumber, exc);
     }
     finally {
         latch.Decrement();
     }
 }
Example #22
0
        private String MarcaCancelado(String path)
        {
            PdfReader reader = new PdfReader(path);
            FileStream fs = null;
            PdfStamper stamp = null;

            var fileOutput = Path.GetTempFileName() + ".pdf";

            string outputPdf = String.Format(fileOutput, Guid.NewGuid().ToString());
            fs = new FileStream(outputPdf, FileMode.CreateNew, FileAccess.Write);
            stamp = new PdfStamper(reader, fs);

            BaseFont bf = BaseFont.CreateFont(@"c:\windows\fonts\arial.ttf", BaseFont.CP1252, true);
            PdfGState gs = new PdfGState();

            gs.FillOpacity = 0.35F;

            gs.StrokeOpacity = 0.35F;
            for (int nPag = 1; nPag <= reader.NumberOfPages; nPag++)
            {

                Rectangle tamPagina = reader.GetPageSizeWithRotation(nPag);
                PdfContentByte over = stamp.GetOverContent(nPag);
                over.BeginText();
                WriteTextToDocument(bf, tamPagina, over, gs, "CANCELADO");
                over.EndText();

            }

            reader.Close();
            if (stamp != null) stamp.Close();
            if (fs != null) fs.Close();

            return fileOutput;
        }
Example #23
0
        private void InsertCharacteristics(PdfStamper Stamper, string str, int X, int Y)
        {
            iTextSharp.text.pdf.PdfContentByte underContent;
            underContent = Stamper.GetOverContent(1);

            PdfTemplate template = underContent.CreateTemplate(500, 300);
            template.BeginText();
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            template.SetFontAndSize(bf, 9);
            template.SetTextMatrix(100, 100);
            template.ShowText(str);
            template.EndText();
            underContent.AddTemplate(template, X, Y);
        }
Example #24
0
        public byte[] WriteToPdfForEmployeeDaily(string sourceFile, CSList<TimeProjectHours> projects, TimeEmployees employee, DateTime dt)
        {
            var reader = new PdfReader(sourceFile);

            using (var memoryStream = new MemoryStream())
            {
                // PDFStamper is the class we use from iTextSharp to alter an existing PDF.
                var pdfStamper = new PdfStamper(reader, memoryStream);

                Rectangle pageSize = reader.GetPageSizeWithRotation(1);

                PdfContentByte pdfPageContents = pdfStamper.GetOverContent(1);
                pdfPageContents.BeginText(); // Start working with text.

                BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER, Encoding.ASCII.EncodingName, false);
                pdfPageContents.SetFontAndSize(baseFont, 11); // 11 point font
                pdfPageContents.SetRGBColorFill(0, 0, 0);

                // Note: The x,y of the Pdf Matrix is from bottom left corner.
                // This command tells iTextSharp to write the text at a certain location with a certain angle.
                // Again, this will angle the text from bottom left corner to top right corner and it will
                // place the text in the middle of the page.
                //
                //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, playerName, pageSize.Width / 2, (pageSize.Height / 2) + 115, 0);
                //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, teamName, pageSize.Width / 2, (pageSize.Height / 2) + 80, 0);

                //user Name
                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, employee.FirstName + " " + employee.LastName + " (AIS-0" + employee.TimeEmployeeID + ")", 155, (pageSize.Height - 168), 0);

                //Date of report
                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, dt.ToShortDateString(), 155, (pageSize.Height - 188), 0);

                int yPos = 241;
                int totalHours = 0;
                foreach (var timeProjectHourse in projects)
                {
                    TimeResources resource = TimeResources.ReadFirst("TimeResourceID = @TimeResourceID", "@TimeResourceID", timeProjectHourse.TimeResourceID);
                    TimeAISCodes classCode = TimeAISCodes.ReadFirst("TimeAISCodeID = @TimeAISCodeID", "@TimeAISCodeID", resource.TimeAISCodeID);

                    TimeProjects project = TimeProjects.ReadFirst("TimeProjectID = @TimeProjectID", "@TimeProjectID", timeProjectHourse.TimeProjectID);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, project.ProjectNumber, 55, (pageSize.Height - yPos), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, classCode.AISCode, 125, (pageSize.Height - yPos), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, project.ProjectName, 185, (pageSize.Height - yPos), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, timeProjectHourse.HoursOfWork.ToString(), 500, (pageSize.Height - yPos), 0);

                    //increment the total hours
                    totalHours += timeProjectHourse.HoursOfWork;

                    yPos += 20;
                }

                //Total

                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, totalHours.ToString(), 500, (pageSize.Height - 685), 0);

                pdfPageContents.EndText(); // Done working with text
                pdfStamper.FormFlattening = true; // enable this if you want the PDF flattened.
                pdfStamper.Close(); // Always close the stamper or you'll have a 0 byte stream.

                return memoryStream.ToArray();
            }
        }
Example #25
0
        public Respuesta find(byte[] pdf, string text)
        {
            int coincidences = 0;
            List<string> cadenas = new List<string>();
            List<WordFine> renglones = new List<WordFine>();
            if (String.IsNullOrEmpty(text))
                return new Respuesta();

            MyLocationTextExtractionStrategy txt = new MyLocationTextExtractionStrategy(text);
            LocationTextExtractionStrategyEx st = new LocationTextExtractionStrategyEx();
            Stream inputPdfStream = new MemoryStream(pdf);
            MemoryStream outPdfStream = new MemoryStream();

            PdfReader reader = new PdfReader(inputPdfStream);
            using (PdfStamper stamper = new PdfStamper(reader, outPdfStream))
            {
                for (int i = 1; i < reader.NumberOfPages + 1; i++)
                {

                    txt = new MyLocationTextExtractionStrategy(text);
                    var ex = PdfTextExtractor.GetTextFromPage(reader, i, txt);

                    txt.strings.ForEach(item => { if (item.ToLower().Contains(text.ToLower())) { coincidences++; ; cadenas.Add(item);  } });
                    //coincidences = txt.myPoints.Count();
                    foreach (var item in txt.myPoints)
                    {
                        WordFine itemWord = new WordFine();
                        if (!item.Text.ToLower().Contains(text.ToLower()))
                            continue;

                        //Create a rectangle for the highlight. NOTE: Technically this isn't used but it helps with the quadpoint calculation
                        iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(item.Rect);
                        //Create an array of quad points based on that rectangle. NOTE: The order below doesn't appear to match the actual spec but is what Acrobat produces
                        itemWord.pagina =i;
                        itemWord.cadenas = item.Text;
                        itemWord.coordenada = rect.Left;
                        renglones.Add(itemWord);

                        using (Document doc = new Document())
                        {
                            PdfContentByte over = stamper.GetOverContent(i);

                            over.SaveState();

                            PdfGState gs1 = new PdfGState();
                            gs1.FillOpacity = 0.3f;
                            over.SetGState(gs1);
                            Rectanngulo rectangulo = findInLine(item.Text.ToLower(), text.ToLower(), rect);
                            //over.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height);
                            over.Rectangle(rectangulo.left, rectangulo.bottom, rectangulo.width, rectangulo.height);
                            over.SetColorFill(BaseColor.YELLOW);
                            over.Fill();
                            over.SetColorStroke(BaseColor.BLUE);
                            over.Stroke();

                            over.RestoreState();
                            doc.Close();
                        }
                    }
                }
            }
            return new Respuesta() { coincidences = coincidences, file = outPdfStream.GetBuffer(), text = cadenas, ubicacion= renglones };
        }
Example #26
0
        public List<byte[]> WriteToPdfForProjectWeekly(string sourceFile, CSList<TimeProjectHours> projects, DateTime dt, TimeProjects projectDetails, WeeklyReportResult[] results)
        {
            var pages = new List<byte[]>();

            int totalItemCount = 0;
            int currentLoopCount = 0;
            int totalHours = 0;
            decimal totalCharge = 0;

            int pageCount = 0;
            while (totalItemCount < projects.Count)
            {
                pageCount += 1;
                var reader = new PdfReader(sourceFile);

                using (var memoryStream = new MemoryStream())
                {
                    // PDFStamper is the class we use from iTextSharp to alter an existing PDF.
                    var pdfStamper = new PdfStamper(reader, memoryStream);

                    Rectangle pageSize = reader.GetPageSizeWithRotation(1);

                    PdfContentByte pdfPageContents = pdfStamper.GetOverContent(1);
                    pdfPageContents.BeginText(); // Start working with text.

                    BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, Encoding.ASCII.EncodingName, false);
                    pdfPageContents.SetFontAndSize(baseFont, 10); // 10 point font
                    pdfPageContents.SetRGBColorFill(0, 0, 0);

                    //      //customer
                    //TimeCustomers customer = TimeCustomers.ReadFirst("TimeCustomerID = @TimeCustomerID", "@TimeCustomerID", projectDetails.TimeCustomerID);
                    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, customer.CustomerName, 210, (pageSize.Height - 150), 0);

                    //project name
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, projectDetails.ProjectName, 210, (pageSize.Height - 150), 0);

                    //Project Number
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, projectDetails.ProjectNumber, 525, (pageSize.Height - 150), 0);

                    //Date of report, shows week span
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMMM dd, yyyy}", dt), 210, (pageSize.Height - 172), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMMM dd, yyyy}", dt.AddDays(6)), 525, (pageSize.Height - 172), 0);

                    int yPos = 221;
                    int localLoopCount = 0;
                    foreach (var timeProjectHourse in projects)
                    {
                        if (localLoopCount > currentLoopCount || currentLoopCount == 0)
                        {
                            TimeResources resource = TimeResources.ReadFirst("TimeResourceID = @TimeResourceID", "@TimeResourceID", timeProjectHourse.TimeResourceID);
                            TimeAISCodes classCode = TimeAISCodes.ReadFirst("TimeAISCodeID = @TimeAISCodeID", "@TimeAISCodeID", resource.TimeAISCodeID);
                            TimeDepartments deptCode = TimeDepartments.ReadFirst("TimeDepartmentID = @TimeDepartmentID", "@TimeDepartmentID", timeProjectHourse.TimeDepartmentID);
                            TimeProjects project = TimeProjects.ReadFirst("TimeProjectID = @TimeProjectID", "@TimeProjectID", timeProjectHourse.TimeProjectID);
                            //TimeEmployees employee = TimeEmployees.ReadFirst("TimeEmployeeID = @TimeEmployeeID", "@TimeEmployeeID", timeProjectHourse.TimeEmployeeID);

                            //show the date worked
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMM d}", timeProjectHourse.DateOfWork), 82, (pageSize.Height - yPos), 0);
                            //show the employee id
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "AIS-0" + timeProjectHourse.TimeEmployeeID, 121, (pageSize.Height - yPos), 0);
                            //show the code
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, classCode.AISCode, 176, (pageSize.Height - yPos), 0);
                            //show the function
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, deptCode.DepartmentName, 205, (pageSize.Height - yPos), 0);
                            //show the hours worked
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, timeProjectHourse.HoursOfWork.ToString(), 640, (pageSize.Height - yPos), 0);
                            //show the hourly rate
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:C}", resource.HourlyRate), 662, (pageSize.Height - yPos), 0);

                            decimal totalForDay = timeProjectHourse.HoursOfWork * resource.HourlyRate;

                            //show the total dollars for that day
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:C}", totalForDay), 705, (pageSize.Height - yPos), 0);

                            const int NUM_CHARS_ALLOWED = 65;
                            int numLines = 0;
                            if (timeProjectHourse.Description.Length <= NUM_CHARS_ALLOWED)
                                numLines = 1;
                            else if (timeProjectHourse.Description.Length > NUM_CHARS_ALLOWED && timeProjectHourse.Description.Length <= (NUM_CHARS_ALLOWED * 2))
                                numLines = 2;
                            else if (timeProjectHourse.Description.Length > (NUM_CHARS_ALLOWED * 2) && timeProjectHourse.Description.Length <= (NUM_CHARS_ALLOWED * 3))
                                numLines = 3;
                            else if (timeProjectHourse.Description.Length > (NUM_CHARS_ALLOWED * 3) && timeProjectHourse.Description.Length <= (NUM_CHARS_ALLOWED * 4))
                                numLines = 4;

                            int partCount = numLines;
                            string input = timeProjectHourse.Description;
                            var descResults = new string[partCount];
                            int rem = timeProjectHourse.Description.Length % NUM_CHARS_ALLOWED;
                            for (var i = 0; i < partCount; i++)
                            {
                                if (i == partCount - 1)
                                    descResults[i] = input.Substring(NUM_CHARS_ALLOWED * i, rem);
                                else
                                    descResults[i] = input.Substring(NUM_CHARS_ALLOWED * i, NUM_CHARS_ALLOWED);
                            }

                            for (var l = 0; l < numLines; l++)
                            {
                                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, descResults[l], 325, (pageSize.Height - yPos), 0);
                                yPos += 10;
                            }

                            //increment the total hours
                            totalHours += timeProjectHourse.HoursOfWork;

                            //increment the total charge-out
                            totalCharge += totalForDay;

                            var botPos = (int)(pageSize.Height - yPos);
                            pdfPageContents.SetLineWidth((float).5);
                            pdfPageContents.MoveTo(68, botPos);
                            pdfPageContents.LineTo(pageSize.Width - 38, botPos);
                            pdfPageContents.Stroke();

                            yPos += 10;

                            totalItemCount++;

                            //check to see if we are at the bottom of the page
                            if (yPos > 480) //540
                            {
                                break;
                            }
                        }
                        localLoopCount++;
                    }

                    currentLoopCount = localLoopCount;

                    if (totalItemCount == projects.Count)
                    {
                        //Total
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Totals", 620, (pageSize.Height - yPos), 0);
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, totalHours.ToString(), 640, (pageSize.Height - yPos), 0);
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:C}", totalCharge), 705, (pageSize.Height - yPos), 0);

                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page " + pageCount, 705, (pageSize.Height - (yPos + 20)), 0);
                    }
                    else
                    {
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page " + pageCount, 705, (pageSize.Height - (yPos + 20)), 0);
                    }

                    #region LEGEND SECTION
                    //horizontal
                    pdfPageContents.MoveTo(68, 40);
                    pdfPageContents.LineTo(pageSize.Width - 325, 40);
                    pdfPageContents.Stroke();

                    pdfPageContents.SetLineWidth((float).5);
                    pdfPageContents.MoveTo(68, 55);
                    pdfPageContents.LineTo(pageSize.Width - 325, 55);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 70);
                    pdfPageContents.LineTo(pageSize.Width - 325, 70);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 85);
                    pdfPageContents.LineTo(pageSize.Width - 325, 85);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 100);
                    pdfPageContents.LineTo(pageSize.Width - 325, 100);
                    pdfPageContents.Stroke();
                    //horizontal

                    //vertical
                    pdfPageContents.MoveTo(68, 40);
                    pdfPageContents.LineTo(68, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(191, 40);
                    pdfPageContents.LineTo(191, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(204, 40);
                    pdfPageContents.LineTo(204, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(304, 40);
                    pdfPageContents.LineTo(304, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(318, 40);
                    pdfPageContents.LineTo(318, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(445, 40);
                    pdfPageContents.LineTo(445, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(pageSize.Width - 325, 40);
                    pdfPageContents.LineTo(pageSize.Width - 325, 100);
                    pdfPageContents.Stroke();
                    //end vertical

                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " CODE LEGEND", 70, 105, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " Assistant Project Engineer   B   Software Developer       D   Advanced Specialist Engineer   F+   ", 78, 90, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " General Management           C   Specialist Engineer        D   Report Writing                           R   ", 78, 75, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " Mathematician                     D   User Experience (GUI)  D   Technician                                  T4   ", 78, 60, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "                                                                                                 Technical Meeting                     TM", 78, 45, 0);
                    #endregion

                    pdfPageContents.EndText(); // Done working with text
                    pdfStamper.FormFlattening = true; // enable this if you want the PDF flattened.
                    pdfStamper.Close(); // Always close the stamper or you'll have a 0 byte stream.

                    pages.Add(memoryStream.ToArray());
                }
            }

            return pages;
        }
Example #27
0
        private void InsertBarCode(String pdfFile)
        {
            var pdfOutputFile = new FileStream(FinalFileFormatter(pdfFile), FileMode.Create);
            var pdfReader = new PdfReader(pdfFile);
            var pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
            var overContent = pdfStamper.GetOverContent(1);

            var pageRect = new Rectangle((float)ConvertUtil.INToPdf(10.5), (float)ConvertUtil.INToPdf(12.48));
            DrawBarCode(overContent, pageRect);
            pdfStamper.Close();
            pdfReader.Close();
        }
Example #28
0
        public List<byte[]> WriteToPdfForEmployeeMonthly(string sourceFile, CSList<TimeProjectHours> projects,
            TimeEmployees employee, DateTime dt, int repType)
        {
            var pages = new List<byte[]>();

            int totalItemCount = 0;
            int currentLoopCount = 0;
            int totalHours = 0;

            while (totalItemCount < projects.Count)
            {
                var reader = new PdfReader(sourceFile);

                using (var memoryStream = new MemoryStream())
                {
                    // PDFStamper is the class we use from iTextSharp to alter an existing PDF.
                    var pdfStamper = new PdfStamper(reader, memoryStream);

                    Rectangle pageSize = reader.GetPageSizeWithRotation(1);

                    PdfContentByte pdfPageContents = pdfStamper.GetOverContent(1);
                    pdfPageContents.BeginText(); // Start working with text.

                    BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, Encoding.ASCII.EncodingName, false);
                    if (repType == 2)
                    {
                        pdfPageContents.SetFontAndSize(baseFont, 20); // 20 point font
                        //show the project name for SRED
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Project: " + ddlMonthlyProjectsSRED.SelectedItem, 75,
                            (pageSize.Height - 125), 0);
                    }
                    pdfPageContents.SetFontAndSize(baseFont, 10); // 10 point font
                    pdfPageContents.SetRGBColorFill(0, 0, 0);

                    //Name
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, employee.FirstName + " " + employee.LastName, 210, (pageSize.Height - 150), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "AIS-0" + employee.TimeEmployeeID, 525, (pageSize.Height - 150), 0);

                    //find out how many days are in the month
                    int days = DateTime.DaysInMonth(dt.Year, dt.Month);

                    //Date of report
                    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, dt.ToShortDateString(), 155, (pageSize.Height - 188), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMMM dd, yyyy}", dt), 210, (pageSize.Height - 172), 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMMM dd, yyyy}", dt.AddDays(days - 1)), 525, (pageSize.Height - 172), 0);

                    int yPos = 221;
                    int localLoopCount = 0;
                    foreach (var timeProjectHourse in projects)
                    {
                        if (localLoopCount > currentLoopCount || currentLoopCount == 0)
                        {
                            TimeResources resource = TimeResources.ReadFirst("TimeResourceID = @TimeResourceID", "@TimeResourceID", timeProjectHourse.TimeResourceID);
                            TimeAISCodes classCode = TimeAISCodes.ReadFirst("TimeAISCodeID = @TimeAISCodeID", "@TimeAISCodeID", resource.TimeAISCodeID);
                            TimeDepartments deptCode = TimeDepartments.ReadFirst("TimeDepartmentID = @TimeDepartmentID", "@TimeDepartmentID", timeProjectHourse.TimeDepartmentID);
                            TimeProjects project = TimeProjects.ReadFirst("TimeProjectID = @TimeProjectID", "@TimeProjectID", timeProjectHourse.TimeProjectID);

                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, String.Format("{0:MMM d}", timeProjectHourse.DateOfWork), 70, (pageSize.Height - yPos), 0);
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, project.ProjectNumber, 115, (pageSize.Height - yPos), 0);
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, classCode.AISCode, 175, (pageSize.Height - yPos), 0);

                            //show the function
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, deptCode.DepartmentName, 220, (pageSize.Height - yPos), 0);

                            //show the hours worked
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, timeProjectHourse.HoursOfWork.ToString(), 730, (pageSize.Height - yPos), 0);

                            const int NUM_CHARS_ALLOWED = 85;
                            int numLines = 0;
                            if (timeProjectHourse.Description.Length <= NUM_CHARS_ALLOWED)
                                numLines = 1;
                            else if (timeProjectHourse.Description.Length > NUM_CHARS_ALLOWED && timeProjectHourse.Description.Length <= (NUM_CHARS_ALLOWED * 2))
                                numLines = 2;
                            else if (timeProjectHourse.Description.Length > (NUM_CHARS_ALLOWED * 2) && timeProjectHourse.Description.Length <= (NUM_CHARS_ALLOWED * 3))
                                numLines = 3;

                            int partCount = numLines;
                            string input = timeProjectHourse.Description;
                            var results = new string[partCount];
                            int rem = timeProjectHourse.Description.Length % NUM_CHARS_ALLOWED;
                            for (var i = 0; i < partCount; i++)
                            {
                                if (i == partCount - 1)
                                    results[i] = input.Substring(NUM_CHARS_ALLOWED * i, rem);
                                else
                                    results[i] = input.Substring(NUM_CHARS_ALLOWED * i, NUM_CHARS_ALLOWED);
                            }

                            for (var l = 0; l < numLines; l++)
                            {
                                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, results[l], 345, (pageSize.Height - yPos), 0);
                                yPos += 10;
                            }

                            //increment the total hours
                            totalHours += timeProjectHourse.HoursOfWork;

                            var botPos = (int)(pageSize.Height - yPos);
                            pdfPageContents.SetLineWidth((float).5);
                            pdfPageContents.MoveTo(65, botPos);
                            pdfPageContents.LineTo(pageSize.Width - 35, botPos);
                            pdfPageContents.Stroke();

                            yPos += 10;

                            totalItemCount++;

                            //check to see if we are at the bottom of the page
                            if (yPos > 480) //540
                            {
                                break;
                            }
                        }
                        localLoopCount++;
                    }

                    currentLoopCount = localLoopCount;

                    if (totalItemCount == projects.Count)
                    {
                        //Total
                        pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Total Hours " + totalHours.ToString(), 730, (pageSize.Height - yPos), 0);
                    }

                    #region LEGEND SECTION
                    //horizontal
                    pdfPageContents.MoveTo(68, 40);
                    pdfPageContents.LineTo(pageSize.Width - 325, 40);
                    pdfPageContents.Stroke();

                    pdfPageContents.SetLineWidth((float).5);
                    pdfPageContents.MoveTo(68, 55);
                    pdfPageContents.LineTo(pageSize.Width - 325, 55);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 70);
                    pdfPageContents.LineTo(pageSize.Width - 325, 70);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 85);
                    pdfPageContents.LineTo(pageSize.Width - 325, 85);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(68, 100);
                    pdfPageContents.LineTo(pageSize.Width - 325, 100);
                    pdfPageContents.Stroke();
                    //horizontal

                    //vertical
                    pdfPageContents.MoveTo(68, 40);
                    pdfPageContents.LineTo(68, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(191, 40);
                    pdfPageContents.LineTo(191, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(204, 40);
                    pdfPageContents.LineTo(204, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(304, 40);
                    pdfPageContents.LineTo(304, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(318, 40);
                    pdfPageContents.LineTo(318, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(445, 40);
                    pdfPageContents.LineTo(445, 100);
                    pdfPageContents.Stroke();

                    pdfPageContents.MoveTo(pageSize.Width - 325, 40);
                    pdfPageContents.LineTo(pageSize.Width - 325, 100);
                    pdfPageContents.Stroke();
                    //end vertical

                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " CODE LEGEND", 70, 105, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " Assistant Project Engineer   B   Software Developer       D   Advanced Specialist Engineer   F+   ", 78, 90, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " General Management           C   Specialist Engineer        D   Report Writing                           R   ", 78, 75, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " Mathematician                     D   User Experience (GUI)  D   Technician                                  T4   ", 78, 60, 0);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "                                                                                                 Technical Meeting                     TM", 78, 45, 0);
                    #endregion

                    pdfPageContents.EndText(); // Done working with text
                    pdfStamper.FormFlattening = true; // enable this if you want the PDF flattened.
                    pdfStamper.Close(); // Always close the stamper or you'll have a 0 byte stream.

                    pages.Add(memoryStream.ToArray());
                }
            }

            return pages;
        }
Example #29
0
        public static Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext Database, IAttachmentTarget Data, User CreatorUser, DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
        {
            // Validate Data
            switch (dt.Scope)
            {
                case DocumentTemplate.DocumentTemplateScopes.Device:
                    if (!(Data is Device))
                        throw new ArgumentException("This AttachmentType is configured for Devices only", "Data");
                    break;
                case DocumentTemplate.DocumentTemplateScopes.Job:
                    if (!(Data is Job))
                        throw new ArgumentException("This AttachmentType is configured for Jobs only", "Data");
                    break;
                case DocumentTemplate.DocumentTemplateScopes.User:
                    if (!(Data is User))
                        throw new ArgumentException("This AttachmentType is configured for Users only", "Data");
                    break;
                default:
                    throw new InvalidOperationException("Invalid AttachmentType Scope");
            }

            Database.Configuration.LazyLoadingEnabled = true;

            // Override FlattenFields if Document Template instructs.
            if (dt.FlattenForm)
                FlattenFields = true;

            ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(Database);

            string templateFilename = dt.RepositoryFilename(Database);
            PdfReader pdfReader = new PdfReader(templateFilename);

            MemoryStream pdfGeneratedStream = new MemoryStream();
            PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfGeneratedStream);

            pdfStamper.FormFlattening = FlattenFields;
            pdfStamper.Writer.CloseStream = false;

            IDictionary expressionVariables = Expression.StandardVariables(dt, Database, CreatorUser, TimeStamp, State);

            foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys)
            {
                if (pdfFieldKey.Equals("DiscoAttachmentId", StringComparison.OrdinalIgnoreCase))
                {
                    AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
                    string fieldValue = dt.CreateUniqueIdentifier(Database, Data, CreatorUser, TimeStamp, 0).ToJson();
                    if (FlattenFields)
                        pdfStamper.AcroFields.SetField(pdfFieldKey, String.Empty);
                    else
                        pdfStamper.AcroFields.SetField(pdfFieldKey, fieldValue);

                    IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey);
                    for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
                    {
                        AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];

                        // Create Binary Unique Identifier
                        var pageUniqueId = dt.CreateUniqueIdentifier(Database, Data, CreatorUser, TimeStamp, pdfFieldPosition.page);
                        var pageUniqueIdBytes = pageUniqueId.ToQRCodeBytes();

                        // Encode to QRCode byte array
                        var pageUniqueIdWidth = (int)pdfFieldPosition.position.Width;
                        var pageUniqueIdHeight = (int)pdfFieldPosition.position.Height;
                        var pageUniqueIdEncoded = QRCodeBinaryEncoder.Encode(pageUniqueIdBytes, pageUniqueIdWidth, pageUniqueIdHeight);

                        // Encode byte array to Image
                        var pageUniqueIdImageData = CCITTG4Encoder.Compress(pageUniqueIdEncoded, pageUniqueIdWidth, pageUniqueIdHeight);
                        var pageUniqueIdImage = iTextSharp.text.Image.GetInstance(pageUniqueIdWidth, pageUniqueIdHeight, false, 256, 1, pageUniqueIdImageData, null);

                        // Add to the pdf page
                        pageUniqueIdImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
                        pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pageUniqueIdImage);
                    }
                    // Hide Fields
                    PdfDictionary field = fields.GetValue(0);
                    if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT)
                    {
                        field.Put(PdfName.F, new PdfNumber(6));
                    }
                    else
                    {
                        PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS);
                        foreach (PdfIndirectReference fieldKidRef in fieldKids)
                        {
                            ((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6));
                        }
                    }
                }
                else
                {
                    Expression fieldExpression = null;
                    if (expressionCache.TryGetValue(pdfFieldKey, out fieldExpression))
                    {
                        if (fieldExpression.IsDynamic)
                        {
                            Tuple<string, bool, object> fieldExpressionResult = fieldExpression.Evaluate(Data, expressionVariables);

                            if (fieldExpressionResult.Item3 != null)
                            {
                                IImageExpressionResult imageResult = (fieldExpressionResult.Item3 as IImageExpressionResult);
                                if (imageResult != null)
                                {
                                    // Output Image
                                    AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
                                    IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey);
                                    for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
                                    {
                                        AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];
                                        iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(imageResult.GetImage((int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height));
                                        pdfImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
                                        pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pdfImage);
                                    }
                                    if (!fieldExpressionResult.Item2 && !imageResult.ShowField)
                                    {
                                        // Hide Fields
                                        PdfDictionary field = fields.GetValue(0);
                                        if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT)
                                        {
                                            field.Put(PdfName.F, new PdfNumber(6));
                                        }
                                        else
                                        {
                                            PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS);
                                            foreach (PdfIndirectReference fieldKidRef in fieldKids)
                                            {
                                                ((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6));
                                            }
                                        }
                                    }
                                }
                            }

                            pdfStamper.AcroFields.SetField(pdfFieldKey, fieldExpressionResult.Item1);

                            if (fieldExpressionResult.Item2) // Expression Error
                            {
                                AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
                                for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
                                {
                                    PdfDictionary field = fields.GetValue(pdfFieldOrdinal);
                                    PdfDictionary fieldMK;
                                    if (field.Contains(PdfName.MK))
                                        fieldMK = field.GetAsDict(PdfName.MK);
                                    else
                                    {
                                        fieldMK = new PdfDictionary(PdfName.MK);
                                        field.Put(PdfName.MK, fieldMK);
                                    }
                                    fieldMK.Put(PdfName.BC, new PdfArray(new float[] { 1, 0, 0 }));
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("Pdf template field expressions are out of sync with the expression cache");
                    }
                }
                State.FlushFieldCache();
            }

            pdfStamper.Close();
            pdfReader.Close();

            if (dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job)
            {
                // Write Job Log

                Job j = (Job)Data;
                JobLog jl = new JobLog()
                {
                    JobId = j.Id,
                    TechUserId = CreatorUser.UserId,
                    Timestamp = DateTime.Now
                };
                jl.Comments = string.Format("# Document Generated\r\n**{0}** [{1}]", dt.Description, dt.Id);
                Database.JobLogs.Add(jl);
            }

            pdfGeneratedStream.Position = 0;
            return pdfGeneratedStream;
        }
Example #30
-1
        private string addCompanyLogo(string pdfPath)
        {
            string outputPDFPath = null;
            int clientID = Core.SessionHelper.getClientId();

            string logoPath = string.Format("{0}/ClientLogo/{1}.jpg", ConfigurationManager.AppSettings["appPath"].ToString(), clientID);
            if (File.Exists(logoPath)) {
                outputPDFPath = string.Format("{0}/Temp/{1}.pdf", appPath, Guid.NewGuid());

                using (var inputPdfStream = new FileStream(pdfPath, FileMode.Open))

                using (var outputPdfStream = new FileStream(outputPDFPath, FileMode.Create)) {
                    PdfReader reader = new PdfReader(inputPdfStream);

                    PdfStamper stamper = new PdfStamper(reader, outputPdfStream);

                    PdfContentByte pdfContentByte = stamper.GetOverContent(1);

                    //var image = iTextSharp.text.Image.GetInstance(inputImageStream);
                    var image = iTextSharp.text.Image.GetInstance(logoPath);
                    image.ScaleToFit(100f, 100f);

                    PdfDocument doc = pdfContentByte.PdfDocument;

                    image.SetAbsolutePosition(40f, doc.PageSize.Height - 150f);
                    pdfContentByte.AddImage(image);
                    stamper.Close();
                }
            }
            else {
                outputPDFPath = pdfPath;
            }

            return outputPDFPath;
        }
Example #31
-6
// ---------------------------------------------------------------------------    
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public byte[] ManipulatePdf(byte[] src) {
    // Create a table with named actions
      Font symbol = new Font(Font.FontFamily.SYMBOL, 20);
      PdfPTable table = new PdfPTable(4);
      table.DefaultCell.Border = Rectangle.NO_BORDER;
      table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
      Chunk first = new Chunk( ((char)220).ToString() , symbol);
      first.SetAction(new PdfAction(PdfAction.FIRSTPAGE));
      table.AddCell(new Phrase(first));
      Chunk previous = new Chunk( ((char)172).ToString(), symbol);
      previous.SetAction(new PdfAction(PdfAction.PREVPAGE));
      table.AddCell(new Phrase(previous));
      Chunk next = new Chunk( ((char)174).ToString(), symbol);
      next.SetAction(new PdfAction(PdfAction.NEXTPAGE));
      table.AddCell(new Phrase(next));
      Chunk last = new Chunk( ((char)222).ToString(), symbol);
      last.SetAction(new PdfAction(PdfAction.LASTPAGE));
      table.AddCell(new Phrase(last));
      table.TotalWidth = 120;
      
      // 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 table to each page
          PdfContentByte canvas;
          for (int i = 0; i < reader.NumberOfPages; ) {
            canvas = stamper.GetOverContent(++i);
            table.WriteSelectedRows(0, -1, 696, 36, canvas);
          }
        }
        return ms.ToArray();
      }    
    }