A Rectangle is the representation of a geometric figure.
Inheritance: Element, IElement
コード例 #1
1
// ---------------------------------------------------------------------------    
    /** Implementation of the cellLayout method. */
    public void CellLayout(
        PdfPCell cell, Rectangle position, PdfContentByte[] canvases) 
    {
      writer.DirectContent.LocalDestination(
        name,
        new PdfDestination(PdfDestination.FITH, position.Top)
      );
    }
コード例 #2
1
 public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
 {
     PdfWriter writer = canvases[0].PdfWriter;
     TextField text = new TextField(
         writer, rectangle, FieldName ?? AddBase64Image.NAME
     );
     PdfFormField field = text.GetTextField();
     writer.AddAnnotation(field);
 }
コード例 #3
1
 public void Ellipse(PdfContentByte content, Rectangle rect) {
   content.SaveState();
   content.SetRGBColorFill(0x00, 0x00, 0xFF);
   content.Ellipse(
     rect.Left - 3f, rect.Bottom - 5f,
     rect.Right + 3f, rect.Top + 3f
   );
   content.Fill();
   content.RestoreState();
 }
コード例 #4
0
        public static float[] GetRelativeColumns(Rectangle format)
        {
            float[] relativeWidths;
            if (format == PageSize.A4)
            {
                relativeWidths = new float[]
                {
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F,
                    35.09F
                };
            }
            else
            {
                relativeWidths = new float[] {};
            }

            return relativeWidths;
        }
コード例 #5
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            float effectiveStrWidthFirstPart = 0.0f;


            int    pageN = writer.PageNumber;
            String text  = "Page " + pageN.ToString() + " of ";

            Console.WriteLine("###-->> OnEndPageText = " + text);
            float len = 10.5f;

            iTextSharp.text.Rectangle pageSize = document.PageSize;

            cb.SetRGBColorFill(100, 100, 100);

            cb.BeginText();
            cb.SetFontAndSize(BaseFont.CreateFont(), 10.5f);
            cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin - 10));
            cb.ShowText(text);
            effectiveStrWidthFirstPart = cb.GetEffectiveStringWidth(text, true);
            Console.WriteLine("###-->> Effective Str Width (first part) = " + effectiveStrWidthFirstPart);
            cb.EndText();

            cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin - 10));
        }
コード例 #6
0
        public byte[] JobsReport(User receiver, IEnumerable <Job> jobs)
        {
            var pageSize = new iTextSharp.text.Rectangle(PageSize.A4.Width, PageSize.A4.Height);
            var doc      = new Document(pageSize, 45, 25, 50, 10);

            byte[] byteArray;
            using (var ms = new MemoryStream())
            {
                var pw = PdfWriter.GetInstance(doc, ms);
                doc.Open();
                doc.Add(WriteDocumentTitle(receiver));
                {
                    var jobNumber = 1;
                    foreach (var job in jobs)
                    {
                        WriteJobInfo(doc, job, jobNumber);
                        ++jobNumber;
                    }
                }
                doc.Close();
                byteArray = ms.ToArray();
                ms.Flush();
                ms.Close();
            }
            //Response.Clear();
            //Response.AddHeader("Content-Disposition", "attachment; filename=myfile.pdf");
            //Response.AddHeader("Content-Length", byteArray.Length.ToString());
            //Response.ContentType = "application/octet-stream";
            //Response.BinaryWrite(byteArray);
            return(byteArray);
        }
コード例 #7
0
        public bool SetWatermarkByImage(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left, string userPassWord, string ownerPassWord, int permission, bool HasCover = false)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader = new PdfReader(inputfilepath);

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

                float width  = psize.Width;
                float height = psize.Height;

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                pdfStamper.SetEncryption(false, userPassWord, ownerPassWord, permission);

                PdfContentByte        waterMarkContent;
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);

                image.GrayFill = 20;

                if (left < 0)
                {
                    left = width / 2 - image.Width + left;
                }

                image.SetAbsolutePosition(left, (height / 2 - image.Height) - top);

                for (int i = 1; i <= numberOfPages; i++)
                {
                    if (HasCover && i == 1)
                    {
                        continue;
                    }

                    waterMarkContent = pdfStamper.GetOverContent(i);
                    waterMarkContent.AddImage(image);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
コード例 #8
0
ファイル: clsAllnew.cs プロジェクト: Lewishui/GS_CJDA
        public void ImageDirect(string savename, List <clsFileNanme_info> FilelistResult)
        {
            string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg"; //临时文件路径
            string fileName  = string.Empty;

            {
                fileName = savename;
                Document document = new Document();
                iTextSharp.text.Rectangle page = PageSize.A4;
                float y = page.Height;
                document = new Document(page, 15, 15, 30, 30);
                float docWidth  = page.Width - 15 * 2;
                float docHeight = page.Height - document.BottomMargin - document.TopMargin;

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                document.Open();

                foreach (clsFileNanme_info item in FilelistResult)
                {
                    iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(item.Filpath);
                    float widthSzie            = (page.Width - 30) / img1.Width;
                    if (widthSzie < 1)
                    {
                        img1.ScalePercent(widthSzie * 100);
                    }
                    document.Add(img1);
                }

                document.Close();
            }
        }
コード例 #9
0
// ===========================================================================
    public override void Write(Stream stream) {
      float w = PageSize.A4.Width;
      float h = PageSize.A4.Height;
      Rectangle rect = new Rectangle(-2*w, -2*h, 2*w, 2*h);
      Rectangle crop = new Rectangle(-2 * w, h, -w, 2 * h);      
      // step 1
      using (Document document = new Document(rect)) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.CropBoxSize = crop;
        // step 3
        document.Open();
        // step 4
        PdfContentByte content = writer.DirectContent;
        PdfTemplate template = CreateTemplate(content, rect, 4);
        float adjust;
        while(true) {
          content.AddTemplate(template, -2*w, -2*h);
          adjust = crop.Right + w;
          if (adjust > 2 * w) {
            adjust = crop.Bottom - h;
            if (adjust < - 2 * h)
                break;
            crop = new Rectangle(-2*w, adjust, -w, crop.Bottom);
          }
          else {
            crop = new Rectangle(crop.Right, crop.Bottom, adjust, crop.Top);
          }
          writer.CropBoxSize = crop;
          document.NewPage();
        }
      }
    }
コード例 #10
0
        private void btnPrintLabel_Click(object sender, EventArgs e)
        {
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

            iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 9);

            var pgSize = new iTextSharp.text.Rectangle(300, 100);
            var doc    = new iTextSharp.text.Document(pgSize, 10, 5, 5, 0);

            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Label.pdf", FileMode.Create));

            name    = lblLastName.Text + ", " + lblFirstName.Text;
            id      = " (" + patientId + ")";
            dob     = "\nD.O.B: " + lblDOB.Text;
            sex     = "  Sex: " + lblGender.Text;
            hc      = "\nHCN: " + lblInsNo.Text;
            address = "\nAddress: " + lblAddress.Text.ToUpper() + "\n" + lblCity.Text.ToUpper() + ", " + lblProvince.Text.ToUpper() + ", " + lblPostalCode.Text.ToUpper();
            phone   = "\nPhone Number: " + lblPhone.Text;

            string    par       = name + id + dob + sex + hc + address + phone;
            Paragraph paragraph = new Paragraph(par, times);

            doc.Open();
            doc.Add(paragraph);

            //iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance("health-care-shield-icon.png");
            //png.ScalePercent(20f);
            //png.SetAbsolutePosition(doc.PageSize.Width - 17f - 50f, doc.PageSize.Height - 38f - 38f);
            //doc.Add(png);

            doc.Close();

            System.Diagnostics.Process.Start("Label.pdf");
        }
コード例 #11
0
ファイル: Form1.cs プロジェクト: trippntechnology/tnt.sandbox
        private void Form1_Load(object sender, EventArgs e)
        {
            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 1000f);
            pageSize.BackgroundColor = BaseColor.BLUE;
            Document doc = new Document(pageSize, 72, 72, 144, 144);

//			Document doc = new Document(PageSize.LETTER);
//			Document doc = new Document(PageSize.LETTER.Rotate());

            PdfWriter.GetInstance(doc, new FileStream(@"HelloWorld.pdf", FileMode.Create));

            doc.AddTitle("Hello world example");
            doc.AddSubject("This example shows how to add metadata");
            doc.AddKeywords("Metadata, iText, step 3, tutorial");
            doc.AddCreator("My program using iText");
            doc.AddAuthor("Bruno Lowagie");
            doc.AddHeader("Expires", "0");
            doc.Open();

            doc.Add(new Paragraph("Hello World"));
            doc.Close();

            string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

            webBrowser1.Navigate(string.Concat(appPath, "\\", @"HelloWorld.pdf"));
        }
コード例 #12
0
        public bool GraphConvertPdf(string savename,string savepath,string basepath,string basetype)
        {
            bool flag = true;
            Document doc = new Document();

            savename = PdfClass.PdfFileNameConverter(savename);
            try
            {
                PdfWriter.GetInstance(doc, new FileStream(@savepath + "\\" + savename + ".pdf", FileMode.Create));

                doc.Open();

                int max = Directory.GetFiles(@basepath).Count();
                for (int i = 0; i < max; i++)
                {
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri(@basepath + "\\" + i.ToString() + "." + basetype));
                    iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(image.Width / image.DpiX * 25.4f * 2.834f, image.Height / image.DpiY * 25.4f * 2.834f);

                    doc.SetPageSize(pagesize);
                    image.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
                    image.SetAbsolutePosition(0f, 0f);

                    doc.NewPage();
                    doc.Add(image);

                }
                doc.Close();
            }
            catch
            {
                flag = false;
            }

            return flag;
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: bzy734084360/tool
        public void ImgTransPDF(List <string> imgList, string afterPath)
        {
            List <string> imageList = imgList;
            //生成PDF路径
            string fileName = string.Empty;

            fileName = afterPath;
            //width:794px;height:1090px
            iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(0f, 0f);
            Document document = new Document(page, 1f, 1f, 1f, 1f);
            //设置纸张横向
            //document.SetPageSize(page.Rotate());
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

            for (int i = 0; i < imageList.Count; i++)
            {
                document.Open();
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageList[i]);
                img.ScaleAbsolute(460f, 700f);

                //图片居中
                img.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
                //图片绝对定位
                img.SetAbsolutePosition(55, 30);

                //图片打印到PDF
                writer.DirectContent.AddImage(img);
                document.NewPage();
            }

            document.Close();
        }
コード例 #14
0
        /// <summary>
        /// Draws a rectangular gradient background color.
        /// </summary>
        /// <param name="pdfRowType">Main table's row types</param>
        /// <param name="sharedData">PdfCells Shared Data</param>        
        /// <param name="position">The coordinates of the cell</param>
        /// <param name="canvases">An array of PdfContentByte to add text or graphics</param>
        public static void ApplyGradientBackground(RowType pdfRowType, CellSharedData sharedData, Rectangle position, PdfContentByte[] canvases)
        {
            BaseColor startColor = null;
            BaseColor endColor = null;

            switch (pdfRowType)
            {
                case RowType.HeaderRow:
                    if (sharedData.Template.HeaderBackgroundColor.Count < 2) return;
                    startColor = sharedData.Template.HeaderBackgroundColor[0];
                    endColor = sharedData.Template.HeaderBackgroundColor[1];
                    break;
                case RowType.PreviousPageSummaryRow:
                    if (sharedData.Template.PreviousPageSummaryRowBackgroundColor.Count < 2) return;
                    startColor = sharedData.Template.PreviousPageSummaryRowBackgroundColor[0];
                    endColor = sharedData.Template.PreviousPageSummaryRowBackgroundColor[1];
                    break;
                case RowType.SummaryRow:
                case RowType.AllGroupsSummaryRow:
                    if (sharedData.Template.SummaryRowBackgroundColor.Count < 2) return;
                    startColor = sharedData.Template.SummaryRowBackgroundColor[0];
                    endColor = sharedData.Template.SummaryRowBackgroundColor[1];
                    break;
                case RowType.PageSummaryRow:
                    if (sharedData.Template.PageSummaryRowBackgroundColor.Count < 2) return;
                    startColor = sharedData.Template.PageSummaryRowBackgroundColor[0];
                    endColor = sharedData.Template.PageSummaryRowBackgroundColor[1];
                    break;
            }

            DrawGradientBackground(position, canvases, startColor, endColor);
        }
コード例 #15
0
ファイル: PdfController.cs プロジェクト: smauhourat/pq
        public void TestPdf2()
        {
            string fileTemplate   = Path.Combine(CommonHelper.MapPath("~/Documents/Templates"), ProductQuoteApp.Resources.Resources.FileNamePdfProductQuoteTemplate);
            string fileNameExport = string.Format("productQuote_{0}_{1}.pdf", 1, Guid.NewGuid().ToString());
            string fileExport     = Path.Combine(CommonHelper.MapPath("~/Documents/Export"), fileNameExport);


            PdfReader  reader = new PdfReader(fileTemplate);
            FileStream fs     = new FileStream(fileExport, FileMode.Create, FileAccess.Write);

            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);

            PdfCopy copy = new PdfCopy(document, fs);

            document.Open();

            PdfImportedPage page = null;

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                page = copy.GetImportedPage(reader, i);

                copy.AddPage(page);
            }



            document.Close();
            reader.Close();


            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            FileStream fs2       = new FileStream(fileExport, FileMode.OpenOrCreate, FileAccess.Write);
            Document   document2 = new Document(size);
            PdfWriter  writer    = PdfWriter.GetInstance(document2, fs2);

            document2.Open();

            PdfContentByte cb = writer.DirectContent;
            BaseFont       bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            cb.SetColorFill(BaseColor.BLACK);
            cb.SetFontAndSize(bf, 9);
            string text = "";

            cb.BeginText();

            //text = "Buenos Aires, 15 de septiembre de 2017";
            text = "PRUEBA PRUEBA PRUEBA PRUEBA ";
            cb.ShowTextAligned(Element.ALIGN_RIGHT, text, 0, 0, 0);

            cb.EndText();

            //cb.AddTemplate(page, 0, 0);
            document2.Close();
            fs2.Close();
            writer.Close();
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
コード例 #16
0
        private void SaveBitmaps(Document pdfDocument, iTextSharp.text.Rectangle pdfPageSize, List <Bitmap> bitMaps)
        {
            int pageCount = bitMaps.Count;

            for (int i = 0; i < pageCount; i++)
            {
                System.Drawing.Image bitImg = (System.Drawing.Image)bitMaps[i];

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitImg, BaseColor.WHITE);

                if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height)
                {
                    if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY)
                    {
                        img.ScalePercent(100f);
                        float percentX = (pdfPageSize.Width * 100) / img.ScaledWidth;
                        float percentY = (pdfPageSize.Height * 100) / img.ScaledHeight;

                        img.ScalePercent(percentX, percentY);
                        img.WidthPercentage = 0;
                    }
                    else
                    {
                        img.ScaleToFit(pdfPageSize.Width, pdfPageSize.Height);
                    }
                }

                iTextSharp.text.Rectangle pageRect = new iTextSharp.text.Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);

                pdfDocument.SetPageSize(pageRect);
                pdfDocument.SetMargins(0, 0, 0, 0);
                pdfDocument.NewPage();
                pdfDocument.Add(img);
            }
        }
コード例 #17
0
 /**
  * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(
  *      com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle,
  *      com.lowagie.text.pdf.PdfContentByte[])
  */
 public void CellLayout(
   PdfPCell cell, Rectangle rect, PdfContentByte[] canvas
 )
 {
     PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
     cb.SaveState();
     if (duration < 90)
     {
         cb.SetRGBColorFill(0x7C, 0xFC, 0x00);
     }
     else if (duration > 120)
     {
         cb.SetRGBColorFill(0x8B, 0x00, 0x00);
     }
     else
     {
         cb.SetRGBColorFill(0xFF, 0xA5, 0x00);
     }
     cb.Rectangle(
       rect.Left, rect.Bottom,
       rect.Width * duration / 240, rect.Height
     );
     cb.Fill();
     cb.RestoreState();
 }
コード例 #18
0
        public void Image(List <string> files, string outputPdfPath)
        {
            foreach (string filePatch in files)
            {
                iTextSharp.text.Rectangle pageSize = null;

                using (var srcImage = new Bitmap(filePatch))
                {
                    pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
                }

                using (var ms = new MemoryStream())
                {
                    var document = new Document(pageSize, 0, 0, 0, 0);
                    PdfWriter.GetInstance(document, ms).SetFullCompression();
                    document.Open();
                    var image = iTextSharp.text.Image.GetInstance(filePatch);
                    document.Add(image);
                    document.Close();

                    var fileName = Path.GetFileNameWithoutExtension(filePatch);

                    File.WriteAllBytes($"{outputPdfPath}{fileName}.pdf", ms.ToArray());
                }
            }
        }
コード例 #19
0
        private void CreateBorder(PdfContentByte cb, PdfWriter writer, Document doc)
        {
            iTextSharp.text.Rectangle r = doc.PageSize;
            float left   = r.Left + 30;
            float right  = r.Right - 30;
            float top    = r.Top - 30;
            float bottom = r.Bottom + 30;
            float width  = right - left;
            float height = top - bottom;

            PdfPTable tab = new PdfPTable(1);

            tab.TotalWidth  = width;
            tab.LockedWidth = true;

            PdfPCell t = new PdfPCell(new Phrase(String.Empty));

            t.BackgroundColor = new BaseColor(250, 235, 215);
            t.FixedHeight     = height;
            t.BorderWidth     = 3;
            tab.AddCell(t);
            Paragraph pa = new Paragraph();

            pa.Add(tab);

            float       h    = tab.TotalHeight;
            PdfTemplate temp = cb.CreateTemplate(tab.TotalWidth, h);

            tab.WriteSelectedRows(0, -1, 0.0F, h, temp);
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(temp);
            img.SetAbsolutePosition(30, 30);
            cb.AddImage(img);
        }
コード例 #20
0
ファイル: Materias.cs プロジェクト: SoldierIced/LDE_T
        public void Guardar(Chart chart1 )
        {
            pag++;
            var chartimage = new MemoryStream();

            chart1.SaveImage(chartimage, ChartImageFormat.Png);

            iTextSharp.text.Image Chart_image = iTextSharp.text.Image.GetInstance(chartimage.GetBuffer());

            //  Chart_image.ScalePercent(98.6f);
            // iTextSharp.text.Image Chart_image = iTextSharp.text.Image.GetInstance(chartimage);// 'Dirreccion a la imagen que se hace referencia

            Chart_image.SetAbsolutePosition(x,y);// 'Posicion en el eje cartesiano

               Chart_image.ScaleAbsoluteWidth(270);// 'Ancho de la imagen
            Chart_image.ScaleAbsoluteHeight(160);// 'Altura de la imagen
            doc.Add(Chart_image);// ' Agrega la imagen al documento

            if (pag ==8) { doc.NewPage();
                iTextSharp.text.Rectangle pageType = iTextSharp.text.PageSize.A4;
                PdfContentByte cb = writer.DirectContent;
                cb.MoveTo(marginLeft, marginTop);
                cb.LineTo(1, marginTop);
                cb.Stroke();
               /*

            */
                x = 10; y = 600; pag = 0;cont = 0; }
        }
コード例 #21
0
ファイル: PDFHelper.cs プロジェクト: goto9ccc/DingTalk
        private static MemoryStream SetWaterMark(MemoryStream ms, string filePath, string waterMarkName, string waterMarkAddr = null)
        {
            MemoryStream msWater    = new MemoryStream();
            PdfReader    pdfReader  = null;
            PdfStamper   pdfStamper = null;

            try
            {
                pdfReader  = new PdfReader(filePath);
                pdfStamper = new PdfStamper(pdfReader, msWater);

                int total = pdfReader.NumberOfPages + 1;                    //获取PDF的总页数
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1); //获取第一页
                float          width            = psize.Width;              //PDF页面的宽度,用于计算水印倾斜
                float          height           = psize.Height;
                PdfContentByte waterContent;
                BaseFont       basefont = BaseFont.CreateFont(@"C://Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs       = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    waterContent = pdfStamper.GetOverContent(i); //在内容上方加水印
                                                                 //透明度
                    waterContent.SetGState(gs);
                    //开始写入文本
                    waterContent.BeginText();

                    //waterContent.SetColorFill(BaseColor.RED);
                    waterContent.SetFontAndSize(basefont, 18);

                    waterContent.SetTextMatrix(0, 0);
                    if (waterMarkAddr == null || waterMarkAddr == "")
                    {
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2, 55);
                    }
                    else
                    {
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2 + 100, 55);
                        waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkAddr, width / 2, height / 2 - 100, 55);
                    }
                    waterContent.EndText();
                }
            }
            catch (Exception)
            {
                return(ms);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
            return(msWater);
        }
コード例 #22
0
 public DigitalDocSync(string OutputFile)
 {
     outputFile = OutputFile;
     reader     = new PdfReader(outputFile);
     rectPage   = reader.GetPageSize(1);
     reader.Close();
 }
コード例 #23
0
            public TextChunk(String str, Vector startLocation, Vector endLocation, float charSpaceWidth, iTextSharp.text.Rectangle rect)
            {
                this.text           = str;
                this.startLocation  = startLocation;
                this.endLocation    = endLocation;
                this.charSpaceWidth = charSpaceWidth;

                this.rectangle = rect;

                Vector oVector = endLocation.Subtract(startLocation);

                if (oVector.Length == 0)
                {
                    oVector = new Vector(1, 0, 0);
                }
                orientationVector    = oVector.Normalize();
                orientationMagnitude = (int)(Math.Atan2(orientationVector[Vector.I2], orientationVector[Vector.I1]) * 1000);

                // see http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
                // the two vectors we are crossing are in the same plane, so the result will be purely
                // in the z-axis (out of plane) direction, so we just take the I3 component of the result
                Vector origin = new Vector(0, 0, 1);

                distPerpendicular = (int)(startLocation.Subtract(origin)).Cross(orientationVector)[Vector.I3];

                distParallelStart = orientationVector.Dot(startLocation);
                distParallelEnd   = orientationVector.Dot(endLocation);
            }
コード例 #24
0
        /// <summary>
        /// Save a pdf file in  "../../test.pdf".
        /// </summary>
        /// <param name="deals">Expect Collection of objects that have Name, Address, ProductName and formula.</param>
        public void GenerateReport(IEnumerable<PdfReportModel> deals)
        {
            FileStream fileStream = new FileStream(ReportsPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle pageSize = new Rectangle(PageSize.A4);
            Document reportDocument = new Document(pageSize);
            PdfWriter pdfWriter = PdfWriter.GetInstance(reportDocument, fileStream);
            var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17);

            reportDocument.Open();

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

            this.PutHeadCells(reportTable);

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

            reportDocument.Add(reportTable);
            reportDocument.Close();
        }
コード例 #25
0
        /// <summary>
        /// 合并PDF文件
        /// </summary>
        /// <param name="originalFilePath">原始文件地址</param>
        /// <param name="mergeFilePath">合并文件地址</param>
        /// <param name="newFilePath">生成文件地址</param>
        private void MergePdf(string originalFilePath, string mergeFilePath, string newFilePath)
        {
            string[]         fileList   = { originalFilePath, mergeFilePath };
            List <PdfReader> readerList = new List <PdfReader>();
            PdfReader        reader     = null;

            iTextSharp.text.Rectangle rec      = new iTextSharp.text.Rectangle(1660, 1000);
            iTextSharp.text.Document  document = new iTextSharp.text.Document(rec);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(newFilePath, FileMode.Create));

            document.Open();
            PdfContentByte  cb = writer.DirectContent;
            PdfImportedPage newPage;

            foreach (var item in fileList)
            {
                reader = new PdfReader(item);
                int iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);
                }
                readerList.Add(reader);
            }
            document.Close();
            foreach (var item in readerList)
            {
                item.Dispose();
            }
        }
コード例 #26
0
        public void GetRectAnno()
        {
            string appRootDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;

            string filePath = outputFile;
            int    pageFrom = 0;
            int    pageTo   = 0;

            listaRectangulos.Clear();
            try
            {
                using (PdfReader reader = new PdfReader(filePath))
                {
                    pageTo = reader.NumberOfPages;

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfDictionary page   = reader.GetPageN(i);
                        PdfArray      annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);
                        if (annots != null)
                        {
                            foreach (PdfObject annot in annots.ArrayList)
                            {
                                //abtiene Annotation de PDF File
                                PdfDictionary annotationDic = (PdfDictionary)PdfReader.GetPdfObject(annot);
                                PdfName       subType       = (PdfName)annotationDic.Get(PdfName.SUBTYPE);
                                //solo el subtype highlight
                                if (subType.Equals(PdfName.HIGHLIGHT))
                                {
                                    // Obtiene Quadpoints y Rectángulo de texto resaltado
                                    //Console.Write("HighLight at Rectangle {0} with QuadPoints {1}\n", annotationDic.GetAsArray(PdfName.RECT), annotationDic.GetAsArray(PdfName.QUADPOINTS));


                                    outputData = "HighLight at Rectangle {0} with QuadPoints {1}\n" + annotationDic.GetAsArray(PdfName.RECT) + annotationDic.GetAsArray(PdfName.QUADPOINTS);
                                    //Extraer texto usando la estrategia de rectángulo
                                    PdfArray coordinates = annotationDic.GetAsArray(PdfName.RECT);

                                    iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(float.Parse(coordinates.ArrayList[0].ToString(), CultureInfo.InvariantCulture.NumberFormat), float.Parse(coordinates.ArrayList[1].ToString(), CultureInfo.InvariantCulture.NumberFormat),
                                                                                                   float.Parse(coordinates.ArrayList[2].ToString(), CultureInfo.InvariantCulture.NumberFormat), float.Parse(coordinates.ArrayList[3].ToString(), CultureInfo.InvariantCulture.NumberFormat));

                                    listaRectangulos.Add(rect);


                                    RenderFilter[]          filter = { new RegionTextRenderFilter(rect) };
                                    ITextExtractionStrategy strategy;
                                    StringBuilder           sb = new StringBuilder();


                                    strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
                                    sb.AppendLine(PdfTextExtractor.GetTextFromPage(reader, i, strategy));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #27
0
ファイル: PDFCreator.cs プロジェクト: dibiancoj/ToracLibrary
        /// <summary>
        /// PDF Creator Helper With No Page Base (Don't want to write a page or report (header or footer)
        /// </summary>
        /// <param name="PageSize">Page Size - A4 is a default page size. Use Enum iTextSharp.text.PageSize</param>
        /// <param name="LandscapeMode">Do you want the pdf in landscape</param>
        /// <param name="MarginTop">Top Margin On The Page</param>
        /// <param name="MarginRight">Right Margin On The Page</param>
        /// <param name="MarginBottom">Bottom Margin On The Page</param>
        /// <param name="MarginLeft">Left Margin On The Page</param>
        /// <param name="PageEventHandler">A Page Event Class That Will Raise Any Events You Need</param>
        public PDFCreator(Rectangle PageSize,
                          bool LandscapeMode,
                          float MarginTop,
                          float MarginRight,
                          float MarginBottom,
                          float MarginLeft,
                          PageEventsBase PageEventHandler)
        {
            //create the instance of the ITextSharpDocument
            Doc = new Document(PageSize, MarginLeft, MarginRight, MarginTop, MarginBottom);

            //let's build the memory stream now
            Ms = new MemoryStream();

            //let's create the new writer and attach the document
            Writer = PdfWriter.GetInstance(Doc, Ms);

            //add the page events to my custom class
            if (PageEventHandler != null)
            {
                Writer.PageEvent = PageEventHandler;
            }

            //if you want the pdf in landscape now, then rotate it
            if (LandscapeMode)
            {
                Doc.SetPageSize(PageSize.Rotate());
            }

            //let's open the document so the developer can do whatever they wan't with it
            Doc.Open();
        }
コード例 #28
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            //x/total x pages 第X页/共X页
            int pageN = writer.PageNumber;
            //String text = "Page " + pageN.ToString() + " of ";
            String text = string.Format("Page {0}/total   pages 第{0}页/共   页", CurrentPage.ToString());
            //float len = BF_Light.GetWidthPoint(text, ContentFontSize);
            float len1 = BF_Light.GetWidthPoint("Page x/total ", ContentFontSize);
            float len2 = BF_Light.GetWidthPoint("Page x/total   pages 第x页/共 ", ContentFontSize);

            iTextSharp.text.Rectangle pageSize = document.PageSize;

            //cb.SetRGBColorFill(100, 100, 100);

            cb.BeginText();
            cb.SetFontAndSize(BF_Light, ContentFontSize);
            //make page template in the middle, 90f  is half of all length of page font
            cb.SetTextMatrix(document.PageSize.Width / 2 - 90f, pageSize.GetBottom(20f));
            cb.ShowText(text);

            cb.EndText();

            cb.AddTemplate(template, document.PageSize.Width / 2 - 90f + len1, pageSize.GetBottom(20f));
            cb.AddTemplate(template, document.PageSize.Width / 2 - 90f + len2, pageSize.GetBottom(20f));
        }
コード例 #29
0
ファイル: Form1.cs プロジェクト: latifihsanbulut/DividePDF
        public iTextSharp.text.Rectangle getHalfPageSize(iTextSharp.text.Rectangle pagesize)
        {
            float width  = pagesize.Width;
            float height = pagesize.Height;

            return(new iTextSharp.text.Rectangle(width, height / 2));
        }
コード例 #30
0
        // ---------------------------------------------------------------------------
        /**
         * Creates a PDF document.
         */
        public byte[] CreatePdf()
        {
            Rectangle rect = new Rectangle(-595, -842, 595, 842);
              using (MemoryStream ms = new MemoryStream()) {
            using (Document document = new Document(rect)) {
              // step 2
              PdfWriter writer = PdfWriter.GetInstance(document, ms);
              // step 3
              document.Open();
              // step 4
              PdfContentByte canvas = writer.DirectContent;
              canvas.MoveTo(-595, 0);
              canvas.LineTo(595, 0);
              canvas.MoveTo(0, -842);
              canvas.LineTo(0, 842);
              canvas.Stroke();

              // read the PDF with the logo
              PdfReader reader = new PdfReader(RESOURCE);
              PdfTemplate template = writer.GetImportedPage(reader, 1);
              // add it at different positions using different transformations
              canvas.AddTemplate(template, 0, 0);
              canvas.AddTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
              canvas.AddTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
              canvas.AddTemplate(template, 1, 0, 0.4f, 1, -750, -650);
              canvas.AddTemplate(template, 0, -1, -1, 0, 650, 0);
              canvas.AddTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
            }
            return ms.ToArray();
              }
        }
コード例 #31
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     string RESOURCE = Utility.ResourcePosters;
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         Rectangle rect = new Rectangle(0, 806, 36, 842);
         rect.BackgroundColor = BaseColor.RED;
         document.Add(rect);
         // step 4
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             document.Add(new Paragraph(movie.MovieTitle));
             // Add an image
             document.Add(
               Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"))
             );
         }
     }
 }
コード例 #32
0
        private Rectangle CreatePdfRectangle()
        {
            Rectangle rect = new Rectangle(PageSize.A4);
            rect.BackgroundColor = new BaseColor(System.Drawing.Color.LightGray);

            return rect;
        }
コード例 #33
0
 /**
  * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(com.itextpdf.text.pdf.PdfPCell,
  *      com.itextpdf.text.Rectangle, com.itextpdf.text.pdf.PdfContentByte[])
  */
 virtual public void CellLayout(PdfPCell cell, Rectangle position,
         PdfContentByte[] canvases) {
     float effectivePadding = styleValues.BorderWidthLeft/2 + styleValues.HorBorderSpacing;
     float x1 = position.Left + effectivePadding;
     if (styleValues.IsLastInRow){
         effectivePadding = styleValues.BorderWidthRight/2 + styleValues.HorBorderSpacing;
     } else {
         effectivePadding = styleValues.BorderWidthRight/2;
     }
     float x2 = position.Right - effectivePadding;
     effectivePadding = styleValues.BorderWidthTop/2 + styleValues.VerBorderSpacing;
     float y1 = position.Top - effectivePadding;
     effectivePadding = styleValues.BorderWidthBottom/2;
     float y2 = position.Bottom + effectivePadding;
     PdfContentByte cb = canvases[PdfPTable.LINECANVAS];
     BaseColor color = styleValues.Background;
     if (color != null) {
         cb.SetColorStroke(color);
         cb.SetColorFill(color);
         cb.Rectangle(x1, y1, x2-x1, y2-y1);
         cb.Fill();
     }
     BaseColor borderColor = styleValues.BorderColorLeft;
     float width = styleValues.BorderWidthLeft;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x1, y1); // start leftUpperCorner
         cb.LineTo(x1, y2); // left
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorBottom;
     width = styleValues.BorderWidthBottom;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x1, y2); // left
         cb.LineTo(x2, y2); // bottom
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorRight;
     width = styleValues.BorderWidthRight;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x2, y2); // bottom
         cb.LineTo(x2, y1); // right
         cb.Stroke();
     }
     borderColor = styleValues.BorderColorTop;
     width = styleValues.BorderWidthTop;
     if (borderColor != null && width != 0) {
         cb.SetLineWidth(width);
         cb.SetColorStroke(borderColor);
         cb.MoveTo(x2, y1); // right
         cb.LineTo(x1, y1); // top
         cb.Stroke();
     }
     cb.ResetRGBColorStroke();
 }
コード例 #34
0
        public void PutRectAnno(float lx, float ly, float rx, float ry)
        {
            using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(lx, ly, rx, ry);

                    float[] quad = { rect.Left, rect.Top, rect.Right, rect.Top, rect.Left, rect.Bottom, rect.Right, rect.Bottom };


                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);


                    highlight.Color = BaseColor.YELLOW;



                    if (rect.Width > 0 && rect.Height > 0)
                    {
                        stamper.AddAnnotation(highlight, 1);
                    }


                    stamper.Close();
                }
                fs.Close();
            }
        }
コード例 #35
0
ファイル: Form1.cs プロジェクト: trippntechnology/tnt.sandbox
        private void Form1_Load(object sender, EventArgs e)
        {
            string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 1000f);
            Document document = new Document();

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"HelloWorld.pdf", FileMode.Create));

            document.Open();

            /* chapter05/FoxDogImageTypes.java */
            iText.Image img1 = iText.Image.GetInstance(iText.Image.GetInstance(string.Concat(appPath, "\\", "fox.jpg")));
            img1.Alignment = iText.Image.ALIGN_MIDDLE;
            img1.ScaleAbsolute(100f, 100f);
            document.Add(img1);

            /* chapter05/Barcodes.java */
            PdfContentByte cb = writer.DirectContent;

            document.Add(new Paragraph("Barcode 3 of 9"));
            Barcode39 code39 = new Barcode39();

            code39.Code = "ITEXT IN ACTION";
            document.Add(code39.CreateImageWithBarcode(cb, null, null));

            document.Close();

            webBrowser1.Navigate(string.Concat(appPath, "\\", @"HelloWorld.pdf"));
        }
        /// <summary>
        /// Obtiene el texto contenido en un pdf en función del parámetro facilitado.
        /// </summary>
        /// <param name="renderInfo">Información para la obtención del texto.</param>
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);

            LineSegment segment = renderInfo.GetBaseline();

            if (renderInfo.GetRise() != 0)
            {
                // remove the rise from the baseline - we do this because the text from a
                // super /subscript render operations should probably be considered as part
                // of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }

            var ll = renderInfo.GetDescentLine().GetStartPoint();         // lower left
            var ur = renderInfo.GetAscentLine().GetEndPoint();            // upper right

            string text = renderInfo.GetText();                           //mirando

            string fillColor   = renderInfo.GetFillColor()?.ToString();   // Color del texto.
            string strokeColor = renderInfo.GetStrokeColor()?.ToString(); // Color del texto.

            Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
            Vector topRight    = renderInfo.GetAscentLine().GetEndPoint();

            iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
            double fontSize = Math.Round(rect.Height);                  // Tamaño de la fuente a partir del rectángulo extraído.

            string fontName = renderInfo.GetFont()?.PostscriptFontName; //Nombre de la fuente.

            //base._PdfTextChunks.Add(new PdfTextChunk(renderInfo.GetText(), base.tclStrat.CreateLocation(renderInfo, segment), ll, ur));
            _PdfColorFontTextChunks.Add(new PdfColorFontTextChunk(renderInfo.GetText(), base.tclStrat.CreateLocation(renderInfo, segment), ll, ur, fillColor, strokeColor, fontName, fontSize));
        }
コード例 #37
0
        //this function is capable of taking multiple tiff images from a directory
        //and processing each tiff frame by frame
        private void AddTiff(Document pdfDocument, iTextSharp.text.Rectangle pdfPageSize, String tiffPath)
        {
            RandomAccessFileOrArray ra = new RandomAccessFileOrArray(tiffPath);
            int pageCount = TiffImage.GetNumberOfPages(ra);

            for (int i = 1; i <= pageCount; i++)
            {
                iTextSharp.text.Image img = TiffImage.GetTiffImage(ra, i);

                if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height)
                {
                    img.SetDpi(2, 2);

                    if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY)
                    {
                        float percentX = (pdfPageSize.Width * 100) / img.ScaledWidth;
                        float percentY = (pdfPageSize.Height * 100) / img.ScaledHeight;

                        img.ScalePercent(percentX, percentY);
                        img.WidthPercentage = 0;
                    }
                    else
                    {
                        img.ScaleToFit(pdfPageSize.Width, pdfPageSize.Height);
                    }
                }

                iTextSharp.text.Rectangle pageRect = new iTextSharp.text.Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);

                pdfDocument.SetPageSize(pageRect);
                pdfDocument.SetMargins(0, 0, 0, 0);
                pdfDocument.NewPage();
                pdfDocument.Add(img);
            }
        }
コード例 #38
0
        /**
         *
         * @see com.itextpdf.text.pdf.parser.RenderListener#renderText(com.itextpdf.text.pdf.parser.TextRenderInfo)
         */
        public virtual void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment segment = renderInfo.GetBaseline();

            if (renderInfo.GetRise() != 0)
            { // remove the rise from the baseline - we do this because the text from a super/subscript render operations should probably be considered as part of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }
            //TextChunk location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth());
            //locationalResult.Add(location);

            //base.RenderText(renderInfo);


            //Get the bounding box for the chunk of text
            var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
            var topRight   = renderInfo.GetAscentLine().GetEndPoint();

            //Create a rectangle from it
            var rect = new iTextSharp.text.Rectangle(
                bottomLeft[Vector.I1],
                bottomLeft[Vector.I2],
                topRight[Vector.I1],
                topRight[Vector.I2]
                );

            TextChunk location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth(), rect);

            locationalResult.Add(location);
        }
コード例 #39
0
ファイル: PDFEdit.cs プロジェクト: mattwang137/PDFEditor
            //Automatically called for each chunk of text in the PDF
            public override void RenderText(TextRenderInfo renderInfo)
            {
                base.RenderText(renderInfo);
                //See if the current chunk contains the text
                var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);

                //If not found bail
                if (startPosition < 0)
                {
                    return;
                }

                //Grab the individual characters
                var chars = renderInfo.GetCharacterRenderInfos().Skip(startPosition).Take(this.TextToSearchFor.Length).ToList();

                //Grab the first and last character
                var firstChar = chars.First();
                var lastChar  = chars.Last();


                //Get the bounding box for the chunk of text
                var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
                var topRight   = lastChar.GetAscentLine().GetEndPoint();

                //Create a rectangle from it
                var rect = new iTextSharp.text.Rectangle(bottomLeft[Vector.I1], bottomLeft[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);

                //Add this to our main collection
                this.myPoints.Add(new RectAndText(rect, this.TextToSearchFor));
            }
コード例 #40
0
        public static byte[] GetPdf()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();

                    int i = 0;
                    foreach (var fieldName in FieldNames)
                    {
                        var rectangle = new Rectangle(20, 800 - i * 40, 40, 780 - i * 40);
                        var checkbox = new RadioCheckField(
                            writer, rectangle, fieldName, ON_STATE
                        );
                        checkbox.CheckType = RadioCheckField.TYPE_CHECK;
                        PdfFormField field = checkbox.CheckField;
                        writer.AddAnnotation(field);
                        ++i;
                    }

                    // add textbox field for sanity-check
                    var textField = new TextField(
                        writer,
                        new Rectangle(20, 800 - i * 40, 400, 780 - i * 40),
                        TEXT_FIELD
                    );
                    writer.AddAnnotation(textField.GetTextField());
                }
                return ms.ToArray();
            }
        }
コード例 #41
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            // cell height
            float cellHeight = document.TopMargin;

            // PDF document size
            iTextSharp.text.Rectangle page = document.PageSize;

            // create two column table
            PdfPTable head = new PdfPTable(2);

            head.TotalWidth = page.Width;
            int pageN = writer.PageNumber;
            // add image; PdfPCell() overload sizes image to fit cell
            PdfPCell c = new PdfPCell(ImageHeader);

            c.HorizontalAlignment = Element.ALIGN_RIGHT;
            //  c.FixedHeight = cellHeight;
            String text = "Pagina " + writer.PageNumber;

            c.Border = PdfPCell.NO_BORDER;
            head.AddCell(c);

            // add the header text
            c = new PdfPCell(new Phrase(
                                 Titolo + " " +
                                 DateTime.Now.ToString("dd-MM-yyyy HH:mm"),
                                 new iTextSharp.text.Font(iTextSharp.text.Font.TIMES_ROMAN, 9)
                                 ));
            c.Border            = PdfPCell.NO_BORDER;
            c.VerticalAlignment = Element.ALIGN_BOTTOM;
            c.FixedHeight       = cellHeight;
            head.AddCell(c);
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            cb = writer.DirectContent;;
            cb.SetFontAndSize(bf, 7);
            cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
            cb.ShowText(text);
            cb.EndText();
            PdfTemplate footerTemplate;

            footerTemplate = cb.CreateTemplate(50, 50);
            float len = bf.GetWidthPoint(text, 12);

            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));

            // since the table header is implemented using a PdfPTable, we call
            // WriteSelectedRows(), which requires absolute positions!
            head.WriteSelectedRows(
                0, -1, // first/last row; -1 flags all write all rows
                0,     // left offset
                      // ** bottom** yPos of the table
                page.Height - cellHeight + head.TotalHeight,
                writer.DirectContent
                );
        }
コード例 #42
0
        static PdfSignatureAppearance CreateSignatureAppearance(PdfStamper stamper, Signature signature)
        {
            PdfSignatureAppearance signatureAppearance = stamper.SignatureAppearance;

            signatureAppearance.Reason   = signature.Reason;
            signatureAppearance.Contact  = signature.Contact;
            signatureAppearance.Location = signature.Location;
            signatureAppearance.SignDate = DateTime.UtcNow.Date;

            var pageRect = stamper.Reader.GetPageSize(signature.Page);

            var random        = new Random();
            int signatureLeft = random.Next(20, (int)pageRect.Width - 400 - 20);
            int signatureTop  = random.Next(20, (int)pageRect.Height - 75 - 20);

            var signatureRect = new iTextSharp.text.Rectangle(
                (float)signatureLeft,
                (float)signatureTop,
                (float)signatureLeft + 400,
                (float)signatureTop + 75);

            signatureAppearance.Acro6Layers = true;
            signatureAppearance.Layer2Text  = signature.CustomText;
            signatureAppearance.Render      = PdfSignatureAppearance.SignatureRender.Description;
            signatureAppearance.SetVisibleSignature(signatureRect, signature.Page, null);

            return(signatureAppearance);
        }
コード例 #43
0
        private void Print_btn_click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("Ticket.pdf", FileMode.Create, FileAccess.Write, FileShare.None);

            iTextSharp.text.Rectangle rec2 = new iTextSharp.text.Rectangle(PageSize.A4);
            rec2.BackgroundColor = new BaseColor(Color.LightBlue);
            Document  doc = new Document(rec2);
            PdfWriter wri = PdfWriter.GetInstance(doc, fs);

            doc.Open();
            iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("logo.png");
            PNG.ScalePercent(40f);
            PNG.SetAbsolutePosition(doc.PageSize.Width - 46f - 75f, doc.PageSize.Height - 36f - 105f);
            Paragraph par  = new Paragraph("                                                               Railway Enquiry System ");
            Paragraph par1 = new Paragraph("                                                                    Ticket ID : " + Ticketidtbox.Text + "\nTrain Name : " + TrainNametbox.Text + "\nFrom : " + Fromtbox.Text + "                              To : " + totbox.Text + "\nJourney Date : " + JourneydateTP.Text + "                        Starting Time : " + Stimetbox.Text);
            Paragraph par2 = new Paragraph("Passenger Name : " + pnametbox.Text + "                                   Reaching Time : " + RTimetbox.Text + "\nGender : " + pgendertbox.Text + "\nNumber of Seat : " + Seatstbox.Text + "                                                     Seat Type : " + snametbox.Text + "\nGender : " + pgendertbox.Text + "\nPrice : " + pricetbox.Text);

            doc.Add(PNG);
            doc.Add(par);
            doc.Add(par1);
            doc.Add(par2);
            doc.Close();
            MessageBox.Show("Successfully Ticket Printed", "Print Info");
            this.Printbtn.Enabled = false;
        }
コード例 #44
0
        //private static IDictionary<string, string> Meta2Parameters(Texxtoor.BaseLibrary.Pdf2Epub.MetaData data) {
        //  IDictionary<string, string> dictionary = new Dictionary<string, string>();
        //  dictionary.Add("##Author##", data.Author);
        //  dictionary.Add("##Title##", data.Title);
        //  dictionary.Add("##Date##", data.Date);
        //  dictionary.Add("##UUID##", Guid.NewGuid().ToString());
        //  return dictionary;
        //}

        private static void ParseHtml(Document doc, StringReader html, StyleSheet css, List <Bitmap> images)
        {
            iTextSharp.text.Rectangle mySize = null;
            var htmlWorker = new HTMLWorker(doc);

            htmlWorker.SetStyleSheet(css);
            //htmlWorker.Parse(html);
            var objects = HTMLWorker.ParseToList(html, css);

            foreach (var element in objects)
            {
                doc.Add(element);
            }
            mySize = doc.PageSize;
            if (images.Count > 0)
            {
                for (int i = 0; i <= images.Count - 1; i++)
                {
                    System.Drawing.Image  mySource = (Bitmap)images[i];
                    iTextSharp.text.Image myImage  = iTextSharp.text.Image.GetInstance(mySource, System.Drawing.Imaging.ImageFormat.Png);
                    myImage.ScaleAbsolute(400, 300);
                    doc.Add(myImage);
                }
            }
        }
コード例 #45
0
        public static void SetPageBackgroundColor(this PdfInfo pdfInfo, int pageNumber, BaseColor color = null)
        {
            if (color == null)
            {
                color = BaseColor.WHITE;
            }

            using (PdfReader reader = new PdfReader(pdfInfo.GetBytes()))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (PdfStamper stamper = new PdfStamper(reader, ms))
                    {
                        PageInfo pageInfo = pdfInfo.GetPage(pageNumber);

                        Rectangle rectangle = new Rectangle(0, 0, Utilities.MillimetersToPoints(pageInfo.PageWidth),
                                                            Utilities.MillimetersToPoints(pageInfo.PageHeight), 0)
                        {
                            BackgroundColor = color
                        };

                        var cb = stamper.GetUnderContent(pageNumber);
                        cb.Rectangle(rectangle);
                    }

                    pdfInfo.UpdateBytes(ms.ToArray());
                }
            }
        }
コード例 #46
0
        public void SetSignatureBox(float llx, float lly, float urx, float ury)
        {
            SignatureBox = new Rectangle(llx, lly, urx, ury) 
            { 
                BorderColor = BaseColor.BLACK, Border = Rectangle.BOX, BorderWidth = 1
            };

        }
コード例 #47
0
        virtual public void test() {
            PdfReader reader = TestResourceUtils.GetResourceAsPdfReader(TEST_RESOURCES_PATH, "user10.pdf");
            Rectangle rectangle = new Rectangle(71, 792 - 84, 225, 792 - 75);
            RenderFilter filter = new RegionTextRenderFilter(rectangle);
            String txt = PdfTextExtractor.GetTextFromPage(reader, 1, new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter));

            Assert.AreEqual("Pname Dname Email Address", txt);
        }
コード例 #48
0
ファイル: Pdf3D.cs プロジェクト: kuujinbo/iTextInAction2Ed
        // ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
              using (Document document = new Document()) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, stream);
            // step 3
            document.Open();
            // step 4
            Rectangle rect = new Rectangle(100, 400, 500, 800);
            rect.Border = Rectangle.BOX;
            rect.BorderWidth = 0.5f;
            rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
            document.Add(rect);

            PdfIndirectObject streamObject = null;
            using (FileStream fs =
              new FileStream(RESOURCE, FileMode.Open, FileAccess.Read))
            {
              PdfStream stream3D = new PdfStream(fs, writer);

              stream3D.Put(PdfName.TYPE, new PdfName("3D"));
              stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
              stream3D.FlateCompress();
              streamObject = writer.AddToBody(stream3D);
              stream3D.WriteLength();
            }

            PdfDictionary dict3D = new PdfDictionary();
            dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
            dict3D.Put(new PdfName("XN"), new PdfString("Default"));
            dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
            dict3D.Put(new PdfName("MS"), PdfName.M);
            dict3D.Put(
              new PdfName("C2W"),
              new PdfArray(
            new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }
              )
            );
            dict3D.Put(PdfName.CO, new PdfNumber(235));

            PdfIndirectObject dictObject = writer.AddToBody(dict3D);

            PdfAnnotation annot = new PdfAnnotation(writer, rect);
            annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
            annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
            annot.Put(PdfName.TYPE, PdfName.ANNOT);
            annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
            annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
            PdfAppearance ap = writer.DirectContent.CreateAppearance(
              rect.Width, rect.Height
            );
            annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
            annot.SetPage();

            writer.AddAnnotation(annot);
              }
        }
コード例 #49
0
// ---------------------------------------------------------------------------    
    /**
     * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(
     * com.lowagie.text.pdf.PdfPCell,
     * com.lowagie.text.Rectangle, 
     * com.lowagie.text.pdf.PdfContentByte[]
     * )
     */
    public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb)
    {
      parent.AddKid(kid);
      kid.SetWidget(
        new Rectangle(rect.GetLeft(padding), rect.GetBottom(padding),
        rect.GetRight(padding), rect.GetTop(padding)),
        PdfAnnotation.HIGHLIGHT_INVERT
      );
    }
コード例 #50
0
 // ---------------------------------------------------------------------------
 /** Implementation of the cellLayout method. */
 public void CellLayout(
 PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
 {
     writer.AddAnnotation(new PdfAnnotation(
     writer,
     position.Left, position.Bottom, position.Right, position.Top,
     action
       ));
 }
コード例 #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PdfGenerator"/> class.
 /// </summary>
 public PdfGenerator()
 {
     
     Rectangle rect = new Rectangle(width * DPI, height * DPI);
     this.document = new Document(rect, hMargin, hMargin, vMargin, vMargin);
     this.ms = new MemoryStream();
     this.writer = PdfWriter.GetInstance(this.document, this.ms);
     this.document.Open();
 }
コード例 #52
0
ファイル: PDFCreator.cs プロジェクト: dibiancoj/ToracLibrary
 /// <summary>
 /// PDF Creator Helper With No Page Base (Don't want to write a page or report (header or footer)
 /// </summary>
 /// <param name="PageSize">Page Size - A4 is a default page size. Use Enum iTextSharp.text.PageSize</param>
 /// <param name="LandscapeMode">Do you want the pdf in landscape</param>
 /// <param name="MarginTop">Top Margin On The Page</param>
 /// <param name="MarginRight">Right Margin On The Page</param>
 /// <param name="MarginBottom">Bottom Margin On The Page</param>
 /// <param name="MarginLeft">Left Margin On The Page</param>
 public PDFCreator(Rectangle PageSize,
                   bool LandscapeMode,
                   float MarginTop,
                   float MarginRight,
                   float MarginBottom,
                   float MarginLeft)
     : this(PageSize, LandscapeMode, MarginTop, MarginRight, MarginBottom, MarginLeft, null)
 {
 }
コード例 #53
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        // draw squares
        CreateSquares(canvas, 50, 720, 80, 20);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase(
            "Methods MoveTo(), LineTo(), stroke(), closePathStroke(), Fill(), and closePathFill()"
          ),
          50, 700, 0
        );
        // draw Bezier curves
        createBezierCurves(canvas, 70, 600, 80, 670, 140, 690, 160, 630, 160);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase("Different CurveTo() methods, followed by stroke()"),
          50, 580, 0
        );
        // draw stars and circles
        CreateStarsAndCircles(canvas, 50, 470, 40, 20);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase(
            "Methods Fill(), eoFill(), NewPath(), FillStroke(), and EoFillStroke()"
          ),
          50, 450, 0
        );
        // draw different shapes using convenience methods
        canvas.SaveState();
        canvas.SetColorStroke(new GrayColor(0.2f));
        canvas.SetColorFill(new GrayColor(0.9f));
        canvas.Arc(50, 270, 150, 330, 45, 270);
        canvas.Ellipse(170, 270, 270, 330);
        canvas.Circle(320, 300, 30);
        canvas.RoundRectangle(370, 270, 80, 60, 20);
        canvas.FillStroke();
        canvas.RestoreState();
        Rectangle rect = new Rectangle(470, 270, 550, 330);
        rect.BorderWidthBottom = 10;
        rect.BorderColorBottom = new GrayColor(0f);
        rect.BorderWidthLeft = 4;
        rect.BorderColorLeft = new GrayColor(0.9f);
        rect.BackgroundColor = new GrayColor(0.4f);
        canvas.Rectangle(rect);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase("Convenience methods"), 50, 250, 0
        );
      }
    }
コード例 #54
0
        private bool TextIsInRectangle(PdfReader reader, String text, Rectangle rect)
        {

            FilteredTextRenderListener filterListener = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), new RegionTextRenderFilter(rect));

            String extractedText = PdfTextExtractor.GetTextFromPage(reader, 1, filterListener);

            return extractedText.Equals(text);
        }
コード例 #55
0
 public override void OnEndPage(PdfWriter writer, Document document) {
     Rectangle pageSize = writer.PageSize;
     float verticalPosition = writer.GetVerticalPosition(false);
     PdfContentByte canvas = writer.DirectContent;
     Rectangle rect = new Rectangle(0, verticalPosition, pageSize.Right, pageSize.Top);
     rect.Border = Rectangle.BOX;
     rect.BorderWidth = 1;
     rect.BorderColor = BaseColor.BLUE;
     canvas.Rectangle(rect);
 }
コード例 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PdfRenderer"/> class. 
 /// Initialize a new instance of the PDFRenderer class with the specified page type and orientation
 /// </summary>
 /// <param name="pageType">
 /// A String containing the page size name. E.g. A4, letter
 /// </param>
 /// <param name="landscape">
 /// If true the page orientation will be landscape, else potrait
 /// </param>
 /// <param name="componentCodeDescriptionMap">
 /// The map between component code value and description
 /// </param>
 public PdfRenderer(
     string pageType, bool landscape, ComponentCodeDescriptionDictionary componentCodeDescriptionMap)
     : base(componentCodeDescriptionMap, false)
 {
     Rectangle page = PageSize.GetRectangle(pageType);
     if (page != null)
     {
         this._pageSize = landscape ? page.Rotate() : page;
     }
 }
コード例 #57
0
 public static void CreatePdf(string fileName)
 {
     Rectangle pagesize = new Rectangle(216f, 720f);
     Document document = new Document(pagesize, 36f, 72f, 108f, 180f);
     FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);
     PdfWriter.GetInstance(document, stream);
     document.Open();
     document.Add(new Paragraph("Hello World"));
     document.Close();
 }
コード例 #58
0
ファイル: PdfResult.cs プロジェクト: tiagomaximo/LiteFx
 public PdfResult(IList rows, string fileName, Type resourceSource, string[] headers, PdfPageEventHelper eventHelper, Rectangle pageSize, Single[] columnsWidth)
 {
     Rows = rows;
     FileName = fileName;
     _headers = headers;
     ResourceSource = resourceSource;
     PageEventHelper = eventHelper;
     DocumentPageSize = pageSize;
     ColumnWidth = columnsWidth;
 }
コード例 #59
0
        /// <summary>
        /// It will show the SaveFileDialog to save the current report's content as a PDF file.
        /// </summary>
        /// <param name="doc">Retrieve it from xps.GetFixedDocumentSequence() or documentViewer.Document</param>
        /// <param name="pageSize">Example: PageSize.A4</param>
        /// <param name="quality">Resolution of the Images in the PDF </param>  
        public static void InteractiveExport(this FixedDocumentSequence doc, Rectangle pageSize, double quality = 1)
        {
            var dlg = new SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Files (.pdf)|*.pdf" };

            var result = dlg.ShowDialog();

            if (result != true) return;
            var filename = dlg.FileName;
            Export(doc, filename, pageSize, quality);
        }
コード例 #60
0
ファイル: PDFDocument.cs プロジェクト: saeednazari/Rubezh
		public PDFDocument(Stream stream, Rectangle pageSize)
		{
			DocumentStream = stream;
			Document = new Document(pageSize);
			PageEventHelper = new PageEventHelper();
			Writer = PdfWriter.GetInstance(Document, stream);
			Writer.PageEvent = PageEventHelper;
			Document.Open();
			Document.AddCreationDate();
		}