SetAbsolutePosition() public méthode

Sets the absolute position of the Image.
public SetAbsolutePosition ( float absoluteX, float absoluteY ) : void
absoluteX float
absoluteY float
Résultat void
Exemple #1
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var retangulo = new iTextSharp.text.Rectangle(765, 765);
            var documento = new Document(retangulo);

            var writer = PdfWriter.GetInstance(documento, new FileStream(@"c:\teste\teste.pdf", FileMode.Create));

            documento.Open();

            var imagemDoTopo = iTextSharp.text.Image.GetInstance(@"c:\teste\imagem.png");

            imagemDoTopo.SetAbsolutePosition(0, 100);
            documento.Add(imagemDoTopo);

            PdfContentByte cb         = writer.DirectContent;
            BaseFont       outraFonte = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false, false);

            cb.BeginText();
            cb.SetFontAndSize(outraFonte, 12);
            cb.SetColorFill(new BaseColor(51, 51, 51));
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TESTE", 50, 35, 50);
            cb.EndText();

            var paramQR = new Dictionary <EncodeHintType, object>();

            paramQR.Add(EncodeHintType.CHARACTER_SET, CharacterSetECI.GetCharacterSetECIByName("UTF-8"));
            BarcodeQRCode qrCodigo = new BarcodeQRCode("https://www.youtube.com/channel/UCcOGfx3w8BRxkfSyZFsW5fQ",
                                                       150, 150, paramQR);

            iTextSharp.text.Image imgBarCode = qrCodigo.GetImage();
            imgBarCode.SetAbsolutePosition(200, 200);
            documento.Add(imgBarCode);

            BarcodeEAN codeEAN13 = null;

            codeEAN13                  = new BarcodeEAN();
            codeEAN13.CodeType         = Barcode.EAN13;
            codeEAN13.ChecksumText     = true;
            codeEAN13.GenerateChecksum = true;
            codeEAN13.BarHeight        = 12;
            codeEAN13.Code             = "1234567890123";
            imgBarCode                 = codeEAN13.CreateImageWithBarcode(cb, null, null);
            imgBarCode.SetAbsolutePosition(150, 150);
            imgBarCode.Alignment = iTextSharp.text.Image.TEXTWRAP;
            documento.Add(imgBarCode);



            documento.Close();
        }
Exemple #2
0
        protected void PrintBarcodes(PdfWriter pdfWriter, Document doc, Purchase purchase)
        {
            PdfPTable table         = new PdfPTable(1);
            var       query         = _purchaseItemRepository.Table;
            var       purchaseItems = query.Where(x => x.PurchaseId == purchase.Id).ToList();

            foreach (var purchaseItem in purchaseItems)
            {
                iTextSharp.text.pdf.PdfContentByte cb = pdfWriter.DirectContent;
                iTextSharp.text.pdf.Barcode128     bc = new Barcode128();
                bc.TextAlignment = Element.ALIGN_LEFT;
                bc.Code          = purchaseItem.EAN; // CommonUtils.GenerateBarCodeEAN13(purchaseItem.Id);
                bc.StartStopText = false;
                bc.CodeType      = iTextSharp.text.pdf.Barcode128.EAN13;
                bc.Extended      = true;

                iTextSharp.text.Image img = bc.CreateImageWithBarcode(cb,
                                                                      iTextSharp.text.BaseColor.Black, iTextSharp.text.BaseColor.Black);

                cb.SetTextMatrix(1.5f, 3.0f);
                img.ScaleToFit(60, 5);
                img.SetAbsolutePosition(1.5f, 1);
                cb.AddImage(img);
                table.AddCell(img);
            }
            doc.Add(table);
        }
    public void demoPDF()
    {
        using (Stream inputPdfStream = new FileStream(Server.MapPath("~") + "/MyFiles/demo.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(Server.MapPath("~") + "/Sign/Sign.png", FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(Server.MapPath("~") + "/MyFiles/Result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new PdfReader(inputPdfStream);

                    int pages = reader.NumberOfPages;

                    for (int i = 0; i < pages; i++)
                    {
                        var stamper        = new PdfStamper(reader, outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(1);

                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                        // image.ScalePercent(18f);
                        image.ScaleAbsolute(100, 30);

                        image.SetAbsolutePosition(300, 310);
                        pdfContentByte.AddImage(image);


                        stamper.Close();
                    }
                }
    }
    public void setPDF()
    {
        string imgpath       = Server.MapPath("~/Sign/21.jpg");
        string pdfpath       = Server.MapPath("~/TemplateStore/Forms/Nf packet.pdf");
        string pdfpathourput = Server.MapPath("~/TemplateStore/Forms/Demo.pdf");

        using (Stream inputPdfStream = new FileStream(pdfpath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(imgpath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(pdfpathourput, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new iTextSharp.text.pdf.PdfReader(inputPdfStream);

                    int val = reader.NumberOfPages;

                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

                    var pdfContentByte = stamper.GetOverContent(1);

                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);

                    image.SetAbsolutePosition(759f, 459f);

                    pdfContentByte.AddImage(image);
                    stamper.Close();
                }
    }
        public byte[] AddWatermark(byte[] bytes, BaseFont bf)
        {
            using (var ms = new MemoryStream(1000 * 1024))
            {
                PdfReader reader = new PdfReader(bytes, password);

                PdfStamper stamper = new PdfStamper(reader, ms);
                stamper.SetEncryption(password, password, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, PdfWriter.STRENGTH40BITS);

                PdfContentByte waterMark;
                int            times = reader.NumberOfPages;


                for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
                {
                    waterMark = stamper.GetOverContent(pageIndex);
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"C:\Users\jmehta7\source\repos\PDFManipulations\PDFManipulations\wwwroot\images\12097871.jpg");
                    img.SetAbsolutePosition(100, 100);
                    waterMark.AddImage(img);
                }
                stamper.FormFlattening = true;


                stamper.Close();

                return(ms.ToArray());
            }
        }
Exemple #6
0
        public void CartDWPdfGenerationforEmail(int cartDWID)
        {
            // Render the view html to a string.
            _shoppingCartSrv.UserVM = UserVM;
            CartDWPdfModel orderVM  = _shoppingCartSrv.GetQuotePdfDetails(cartDWID);
            string         htmlText = (this._htmlViewRenderer.RenderViewToString(this, "../TCPViews/DWCartPdfGenerationWithHTML", orderVM));
            Document       document = new Document(PageSize.A4, 40f, 30f, 20f, 30f);
            string         fname    = cartDWID + ".pdf";

            PdfWriter.GetInstance(document, new FileStream(ConfigurationManager.AppSettings["PdfPath"] + fname, FileMode.Create));
            document.Open();
            iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/PenWorthyLogo.jpg"));
            pdfImage.ScaleToFit(150, 70);
            pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING; pdfImage.SetAbsolutePosition(200, 600);
            document.Add(pdfImage);
            HTMLWorker hw = new HTMLWorker(document);

            hw.Parse(new StringReader(htmlText));
            document.Close();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "inline;filename=" + fname);
            Response.ContentType = "application/pdf";
            Response.WriteFile(ConfigurationManager.AppSettings["PdfPath"] + fname);
            Response.Flush();
            Response.Clear();
            string        toEmail  = UserVM != null ? UserVM.CRMModelProperties.CustEmail : string.Empty;
            List <string> FilePath = Directory.GetFiles(ConfigurationManager.AppSettings["PdfPath"], fname).ToList();

            _emailservice.SendMail("Pdf Attachment", "Thank you for your Order", true, true, FilePath, null, null, toEmail, null, cartDWID);
            // _emailservice.SendTestMail("Pdf Attachment", "Thank you for your Order", true, true, null, null, null, toEmail, null, cartDWID, null, 0, null);
            Response.End();
        }
Exemple #7
0
    public String ConvertVatImageToPdf(string Name)
    {
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Name);
        int pos = Name.LastIndexOf("\\") + 1;

        vatfilename = Name.Substring(pos, Name.Length - pos).Replace(" ", "");
        vatfilename = vatfilename.Remove(vatfilename.LastIndexOf(".") + 1).ToLower();
        vatfilename = DateTime.Now + "-" + vatfilename + "pdf";
        vatfilename = vatfilename.Replace("/", "-").Replace(":", "").Replace(" ", "-");
        string OutPutFile = Server.MapPath(("~/Vat/" + vatfilename));

        using (FileStream fs = new FileStream(OutPutFile, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 0f))
            {
                using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                {
                    doc.Open();
                    image.ScaleToFit(doc.PageSize);
                    image.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
                    image.SetAbsolutePosition((PageSize.A4.Width - image.ScaledWidth) / 2, (PageSize.A4.Height - image.ScaledHeight) / 2);
                    writer.DirectContent.AddImage(image);
                    doc.Close();
                }
            }
        }

        if (File.Exists(Name))
        {
            File.Delete(Name);
        }
        OutPutFile = "/Vat/" + vatfilename;
        return(OutPutFile);
    }
Exemple #8
0
        public byte[] AddWatermark(byte[] bytes, BaseFont bf)
        {
            using (var ms = new MemoryStream(1000 * 1024))
            {
                PdfReader reader = new PdfReader(bytes, password);

                PdfStamper stamper = new PdfStamper(reader, ms);
                stamper.SetEncryption(password, password, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, PdfWriter.STRENGTH40BITS);

                PdfContentByte waterMark;
                int            times = reader.NumberOfPages;

                if (string.IsNullOrWhiteSpace(_environment.WebRootPath))
                {
                    _environment.WebRootPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
                }

                for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
                {
                    waterMark = stamper.GetOverContent(pageIndex);
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(_environment.WebRootPath + "\\images\\12097871.jpg");
                    img.SetAbsolutePosition(100, 100);
                    waterMark.AddImage(img);
                }
                stamper.FormFlattening = true;


                stamper.Close();

                return(ms.ToArray());
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string     WatermarkLocation = @"C:\users\Rifat\Desktop\work\nar.png";
            string     FileLocation      = @"C:\users\Rifat\Desktop\task\x.pdf";
            Document   document          = new Document();
            PdfReader  pdfReader         = new PdfReader(FileLocation);
            PdfStamper stamp             = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileMode.Create));

            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
            img.SetAbsolutePosition(125, 300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)



            PdfContentByte waterMark;

            for (int page = 1; page <= pdfReader.NumberOfPages; page++)
            {
                waterMark = stamp.GetOverContent(page);
                waterMark.AddImage(img);
            }
            stamp.FormFlattening = true;
            stamp.Close();

            // now delete the original file and rename the temp file to the original file
            File.Delete(FileLocation);
            File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);
        }
Exemple #10
0
 public void Logo(string ruta, Document doc)
 {
     iTextSharp.text.Image img = Imagen(ruta);
     img.SetAbsolutePosition(100, 650);
     doc.Add(img);
     img.ScaleAbsolute(25f, 25F);
 }
Exemple #11
0
        /// <summary>
        /// Removes the pagination from the footer.
        /// </summary>
        /// <param name="inputPdf">The pdf to modify.</param>
        /// <param name="outputPdf">The pdf created with removed pagination.</param>
        public static void RemoveFooterPagination(string inputPdf, string outputPdf)
        {
            using (FileStream fs = new FileStream(outputPdf, FileMode.Create, FileAccess.Write))
            {
                //TaggedPdfReaderTool reader = new TaggedPdfReaderTool();
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    reader.ConvertToXml(new PdfReader(inputPdf), ms);

                //} // Not a tagged pdf

                PdfReader  reader  = new PdfReader(inputPdf);
                PdfStamper stamper = new PdfStamper(reader, fs);
                List <PdfCleanUpLocation> cleanUpLocations = new List <PdfCleanUpLocation>();
                int n = reader.NumberOfPages;
                for (int i = 6; i <= n; i++)
                {
                    cleanUpLocations.Add(new PdfCleanUpLocation(i, new iTextSharp.text.Rectangle(400, 0, 440, 40), BaseColor.WHITE));
                }
                PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper);
                cleaner.CleanUp();

                //If clean up does not work add a white image
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Bitmap(120, 20), BaseColor.WHITE);
                image.SetAbsolutePosition(400, 40);
                //Adds the image to the output pdf
                stamper.GetOverContent(1).AddImage(image, true);
                stamper.Close();
                reader.Close();
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            String Folio_val = args[0];
            string path      = Directory.GetCurrentDirectory();
            // String Folio_val = "https://www.google.com";
            //  String Direccion = "http://rppccolimaevidencias.col.gob.mx:8182/evidencia/Certi2?Secuence=" + Folio_val;
            String    Direccion = Folio_val;
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = new QrCode();

            qrEncoder.TryEncode(Direccion, out qrCode);
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
            MemoryStream     ms     = new MemoryStream();

            render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms);
            var imagenTemporal = new Bitmap(ms);
            var imagen         = new Bitmap(imagenTemporal, new Size(new Point(200, 200)));

            imagen.Save(@path + "\\codigo.jpeg", ImageFormat.Jpeg);
            using (Document doc = new Document(PageSize.LETTER, 30f, 20f, 50f, 40f))
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@path + "\\prueba.pdf", FileMode.Create));
                writer.PageEvent = new HeaderFooter();
                doc.Open();
                iTextSharp.text.Image img           = iTextSharp.text.Image.GetInstance(@path + "\\codigo.jpeg");
                iTextSharp.text.Font  _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                img.SetAbsolutePosition(500, 700);
                img.ScaleToFit(50f, 50F);
                doc.Add(img);
                doc.Close();
                writer.Close();
            }
            Console.WriteLine(Folio_val);
        }
        public FileResult Export(string GridHtml)
        {
            var fpath = "";

            try
            {
                using (MemoryStream stream = new System.IO.MemoryStream())
                {
                    // fpath = HttpContext.Server.MapPath("~/PDFFiles/Quotation/");
                    StringReader sr     = new StringReader(GridHtml);
                    Document     pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
                    PdfWriter    writer = PdfWriter.GetInstance(pdfDoc, stream);
                    pdfDoc.Open();
                    iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(HttpContext.Server.MapPath("~/NewCssAndTheme/img/ssmlogo.jpg"));
                    image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                    image1.SetAbsolutePosition(20, 780);
                    image1.ScaleToFit(80f, 80f);

                    pdfDoc.Add(image1);
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
                    pdfDoc.Close();
                    return(File(stream.ToArray(), "application/pdf", "Quotation.pdf"));

                    //  return File(HttpContext.Server.MapPath("~/PDFFiles/Quotation/") , "application/pdf", "Grid.pdf");
                }
            }
            catch (Exception ex)
            {
                ErrorHandlerClass.LogError(ex);
            }
            return(null);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog()
            {
                Filter = "PDF File|*.pdf", ValidateNames = true
            })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER, 10, 10, 42, 35);
                    try
                    {
                        PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                        doc.Open();
                        iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance("12046919_1726331607595049_7849083510719349652_n.jpg");
                        JPG.SetAbsolutePosition((PageSize.LETTER.Width - JPG.ScaledWidth), (JPG.ScaledHeight));

                        JPG.ScalePercent(30f);
                        //JPG.SetAbsolutePosition(0, doc.PageSize.Height - JPG.ScaledHeight);
                        doc.Add(JPG);
                        rtRecibo.SelectAll();
                        rtRecibo.SelectionHangingIndent = 20;
                        doc.Add(new iTextSharp.text.Paragraph(rtRecibo.Text.PadLeft(20)));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        doc.Close();
                    }
                }
            }
        }
Exemple #15
0
        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; }
        }
Exemple #16
0
        public void build()
        {
            try
            {
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + ImageUrl);
                float x          = image.Width;
                float y          = image.Height;
                float retio      = x / y;
                float pageHeight = Document.PageSize.Height;
                if (IsHeader)
                {
                    //fit to screen
                    x = Document.PageSize.Width;
                    y = x / retio;

                    marginBottom = (int)(pageHeight - y);
                }
                image.ScaleToFit(x, x / retio);
                image.SetAbsolutePosition(Left, Top);
                PdfContentByte cb = Writer.DirectContent;
                PdfTemplate    tp = cb.CreateTemplate(x, x / retio);



                tp.AddImage(image);
                cb.AddTemplate(tp, 0, marginBottom);
            }
            catch (Exception e) { }
        }
Exemple #17
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     using (Stream inputPdfStream = new FileStream(Server.MapPath("~") + "/pdf/test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
         using (MemoryStream outputPdfStream = new MemoryStream())
         {
             var reader         = new PdfReader(inputPdfStream);
             var stamper        = new PdfStamper(reader, outputPdfStream);
             var pdfContentByte = stamper.GetOverContent(1);
             for (int i = 0; i < 5; i++)
             {
                 iTextSharp.text.Image image = GetBarcodeImage();
                 image.SetAbsolutePosition(50, 382 + i * 70);
                 pdfContentByte.AddImage(image);
             }
             stamper.Close();
             var newDoc   = GetDocumentStream();
             var byteList = new List <byte[]>();
             byteList.Add(outputPdfStream.ToArray());
             byteList.Add(newDoc.ToArray());
             var mergedPdf = MergePdfForms(byteList);
             Response.Clear();
             Response.AddHeader("content-disposition", "inline;filename=Telekurye.pdf");
             Response.ContentType = "application/pdf";
             Response.BinaryWrite(mergedPdf.ToArray());
             Response.End();
         }
 }
Exemple #18
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();
                }
            }
        }
        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);
        }
Exemple #20
0
        // Установка QR-кода в PDF-файл
        public void PDFStampQRCode(iTextSharp.text.Image QR,      // Изображение (преобразованное из BarcodeQRCode в Image);
                                   int xOffset     = 0,           // Отступ по оси х. За начало отсчета считается левый нижний угол;
                                   int yOffset     = 740,         // Отступ по оси y. За начало отсчета считается левый нижний угол;
                                   string FilePath = "c:\\QRPDF Test Directory\\QRTest_blank.pdf")
        {
            string CopyFileName = FilePath.Substring(0, FilePath.Length - 4) + "_QR.pdf";

            var reader     = new PdfReader(FilePath);
            var fileStream = new FileStream(CopyFileName, FileMode.Create, FileAccess.Write);
            var document   = new Document(reader.GetPageSizeWithRotation(1));
            var writer     = PdfWriter.GetInstance(document, fileStream);

            document.Open();

            for (var i = 1; i <= reader.NumberOfPages; i++)
            {
                document.NewPage();

                var importedPage = writer.GetImportedPage(reader, i);
                var contentByte  = writer.DirectContent;

                contentByte.BeginText();
                QR.SetAbsolutePosition(xOffset, yOffset);
                contentByte.AddImage(QR);
                contentByte.EndText();
                contentByte.AddTemplate(importedPage, 0, 0);
            }

            document.Close();
            writer.Close();
        }
Exemple #21
0
        private void button11_Click(object sender, EventArgs e)
        {
            string ID  = label16.Text;
            string sum = label12.Text;

            dataGridView3.DataSource = FillTable("select * from sold_products where customer_id=" + ID);
            label16.Text             = GetID("select * from customer", "customer_id").ToString();
            Document  doc    = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("Item list " + ID + ".pdf", FileMode.Create));

            doc.Open();
            iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance("pic.jpg");
            png.ScalePercent(25f);
            png.BorderColor = iTextSharp.text.BaseColor.BLACK;
            png.SetAbsolutePosition(doc.PageSize.Width - 200f - 200f, doc.PageSize.Height - 80f - 30f);
            doc.Add(png);
            List      list = new List(List.UNORDERED, 10f);
            Paragraph para = new Paragraph("\n\n");

            doc.Add(para);
            list.Add("User: "******"");
            list.Add("Date Time: " + dateTime + "");
            list.Add("ID Number: " + ID + "");
            list.Add("Customer Name: Respected Customer\n\n\n");
            doc.Add(list);
            PdfPTable table = new PdfPTable(dataGridView3.Columns.Count);

            for (int i = 0; i < dataGridView3.Columns.Count; i++)
            {
                table.AddCell(new Phrase(dataGridView3.Columns[i].HeaderText));
            }
            table.HeaderRows = 1;

            for (int i = 0; i < dataGridView3.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView3.Columns.Count; j++)
                {
                    if (dataGridView3[j, i].Value != null)
                    {
                        table.AddCell(new Phrase(dataGridView3[j, i].Value.ToString()));
                    }
                }
            }
            doc.Add(table);
            Paragraph para0 = new Paragraph("\n\n");

            doc.Add(para0);
            List      list1 = new List(List.UNORDERED, 10f);
            Paragraph para1 = new Paragraph("\n\n");

            list1.Add("Total number of item(s) = " + label3.Text + "");
            list1.Add("Total price = " + sum + "");
            doc.Add(list1);
            para1.IndentationLeft = 40f;
            para1.Add("Thank you! :)");
            doc.Add(para1);
            doc.Close();
            System.Diagnostics.Process.Start("Item list " + ID + ".pdf");
            MessageBox.Show("Pdf Created Successfully!");
        }
        public static void MakePDF(string fileName)
        {
            FileStream fs     = new FileStream(fileName, FileMode.Create);
            Document   doc    = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
            PdfWriter  writer = PdfWriter.GetInstance(doc, fs);

            doc.AddTitle("Sitzplan");

            doc.Open();

            // string tmpPath = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]).Replace("\\bin\\Debug", "\\tmp\\");
            string tmpPath = System.IO.Path.GetTempPath();
            string picName = "Sitzplan-Block{}.png";

            for (int i = 1; i < 7; i++)
            {
                doc.Add(new Paragraph("Block " + Convert.ToString(i)));

                string tmpPicName = picName.Replace("{}", Convert.ToString(i));

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(tmpPath + tmpPicName);
                img.ScaleToFit(PageSize.A4.Rotate());
                img.SetAbsolutePosition(10, 0);
                doc.Add(img);

                doc.NewPage();
            }

            doc.Close();
            writer.Close();
            fs.Close();
        }
Exemple #23
0
        public int AddImage(string imagePath, string titre = null, string stampString = null, string fileNotFoundMessage = null)
        {
            AssertGoodInitialization();

            if (!File.Exists(imagePath))
            {
                CreateMissingFilePage("Photo introuvable", imagePath, fileNotFoundMessage);
            }
            else
            {
                AddNewContentPage();
                CreateStamp(stampString);
                WriteText("\n", null, null, null, false);
                WriteTitle(titre, 1, true, true, false, true);
                iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(imagePath);

                var docHeight = PageSize.A4.Height - _docContent.BottomMargin - _docContent.TopMargin - 150;
                var docWidth  = PageSize.A4.Width - _docContent.LeftMargin - _docContent.RightMargin - 150;
                if (pic.Width > docWidth || pic.Height > docHeight)
                {
                    var scalePercent = docWidth / pic.Width * 100;
                    scalePercent = Math.Min(scalePercent, docHeight / pic.Height * 100);

                    pic.ScalePercent(scalePercent);
                }
                // centrage de l'image
                pic.SetAbsolutePosition((PageSize.A4.Width - pic.ScaledWidth) / 2, (PageSize.A4.Height - pic.ScaledHeight) / 2);
                pic.Border      = iTextSharp.text.Rectangle.BOX;
                pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
                pic.BorderWidth = 1f;
                _docContent.Add(pic);
            }

            return(1);
        }
Exemple #24
0
        public bool AddSealSD(string DocumentPath, string SavePath, string SealIMG)
        {
            try
            {
                string WatermarkLocation = SealIMG;
                // string FileLocation = Server.MapPath(Signed);

                Document   document  = new Document();
                PdfReader  pdfReader = new PdfReader(DocumentPath);
                int        PageCount = pdfReader.NumberOfPages;
                PdfStamper stamp     = new PdfStamper(pdfReader, new FileStream(SavePath, FileMode.Create));

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
                img.SetAbsolutePosition(float.Parse(Seal_AbsolutePosition_X), float.Parse(Seal_AbsolutePosition_Y)); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
                img.ScaleAbsolute(float.Parse(Seal_ScaleAbsolute_W), float.Parse(Seal_ScaleAbsolute_H));
                PdfContentByte waterMark;
                for (int page = PageCount; page <= pdfReader.NumberOfPages; page++)
                {
                    waterMark = stamp.GetOverContent(page);
                    waterMark.AddImage(img);
                }
                stamp.FormFlattening = true;

                stamp.Close();
                document.Close();
                stamp.Close();
                return(true);
            }
            catch (Exception Ex)
            {
                ErrorLog.LogError(Ex);
                return(false);
            }
        }
Exemple #25
0
        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();
        }
Exemple #26
0
        public static void ConvertFirstApproach()
        {
            // creation of the document with a certain size and certain margins
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

            // creation of the different writers
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Users\Mohd\Documents\visual studio 2013\Projects\TiffToPDF\TiffToPDF\tiff.tif.pdf", System.IO.FileMode.Create));

            // load the tiff image and count the total pages
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Users\Mohd\Documents\visual studio 2013\Projects\TiffToPDF\TiffToPDF\tiff.tif");
            int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

            document.Open();
            iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
            for (int k = 0; k < total; ++k)
            {
                bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Jpeg);
                img.SetAbsolutePosition(0, 0);
                img.ScaleAbsolute(500, 500);
                //  img.ScalePercent(72f / img.DpiX * 100);
                img.ScaleAbsoluteHeight(document.PageSize.Height);
                img.ScaleAbsoluteWidth(document.PageSize.Width);
                //    img.CompressionLevel = 1;
                //    img.Deflated = true;
                cb.AddImage(img);

                document.NewPage();
            }
            document.Close();
        }
        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;
        }
Exemple #28
0
        /// <summary>
        /// Add image
        /// </summary>
        private void addImage(StyleInfo styleInfo, float x, float y, float width, float height,
                              RectangleF clipRectangle, byte[] image, string url, string tooltip)
        {
            //add the image with the zoom and position
            iTextSharp.text.Image pdfImge = iTextSharp.text.Image.GetInstance(image);
            pdfImge.ScaleAbsolute(width, height);
            pdfImge.SetAbsolutePosition(x, pageHeight - y - height);
            document.Add(pdfImge);

            //add url
            if (url != null)
            {
                document.Add(new Annotation(x, pageHeight - y, height, width, url));
            }

            //add tooltip
            if (!string.IsNullOrEmpty(tooltip))
            {
                document.Add(new Annotation(x, pageHeight - y, height, width, tooltip));
            }

            //add any required border
            addBorder(styleInfo, x - styleInfo.PaddingLeft, y - styleInfo.PaddingTop, width + styleInfo.PaddingLeft + styleInfo.PaddingRight,
                      height + styleInfo.PaddingTop + styleInfo.PaddingBottom);
        }
        private static void WritePDF(String data, Bitmap barCode)
        {
            Document doc = new Document(PageSize.LETTER);

            try
            {
                PdfWriter.GetInstance(doc, new FileStream(@"C:\Test.pdf", FileMode.Create));
                doc.Open();
                iTextSharp.text.Image bitmap = iTextSharp.text.Image.GetInstance(barCode, System.Drawing.Imaging.ImageFormat.Bmp);
                bitmap.ScalePercent(24f);
                bitmap.SetAbsolutePosition(((doc.PageSize.Width / 2f) - (bitmap.ScaledWidth / 2f)), ((doc.PageSize.Height / 2f) - (bitmap.ScaledHeight / 2f)));
                doc.Add(bitmap);
                doc.NewPage();
                doc.Add(bitmap);
            }
            catch (DocumentException dex)
            {
                Console.Write(dex.Message);
            }
            catch (IOException ioex)
            {
                Console.Write(ioex.Message);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            finally
            {
                doc.Close();
            }
        }
Exemple #30
0
        public bool AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point, string SEALIMG)
        {
            try
            {
                //variables
                string pathin  = inputPdfPath;
                string pathout = outputPdfPath;

                //create PdfReader object to read from the existing document
                using (PdfReader reader = new PdfReader(pathin))
                    //create PdfStamper object to write to get the pages from reader
                    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
                    {
                        //select two pages from the original document
                        reader.SelectPages("1-2");

                        //gettins the page size in order to substract from the iTextSharp coordinates
                        var pageSize = reader.GetPageSize(1);

                        // PdfContentByte from stamper to add content to the pages over the original content
                        PdfContentByte pbover = stamper.GetOverContent(1);

                        //add content to the page using ColumnText
                        Font font = new Font();
                        font.Size = 13;

                        Font font2 = new Font();
                        font2.Size = 7;

                        //setting up the X and Y coordinates of the document
                        int x = point.X;
                        int y = point.Y;

                        x += 113;
                        y  = (int)(pageSize.Height - y);

                        ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
                        ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(reason, font2), 300, 13, 0);

                        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(SEALIMG);
                        img.SetAbsolutePosition(60, 140); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
                        img.ScaleAbsolute(140f, 153.25f);
                        PdfContentByte waterMark;
                        for (int page = 1; page <= reader.NumberOfPages; page++)
                        {
                            waterMark = stamper.GetOverContent(page);
                            waterMark.AddImage(img);
                        }


                        stamper.FormFlattening = true;
                    }
                return(true);
            }
            catch (Exception Ex)
            {
                ErrorLog.LogError(Ex);
                return(false);
            }
        }
Exemple #31
0
        public IcjDocument(string logoFile, string fileName, FileMode fileMode, string output, int marginLeft, int marginRight, int marginTop, int marginBottom)
        {
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            this.marginLeft = marginLeft;
            this.marginRight = marginRight;
            this.marginTop = marginTop;
            this.marginBottom = marginBottom;
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            if (output == "file")
            {
                writer = PdfWriter.GetInstance(document, new FileStream(fileName, fileMode));
            }
            else if (output == "memory")
            {
                stream = new MemoryStream();
                writer = PdfWriter.GetInstance(document, stream);
            }
            width = PageSize.A4.Width - marginLeft - marginRight;
            height = PageSize.A4.Height - marginTop - marginBottom;

            jpg = iTextSharp.text.Image.GetInstance(logoFile);

            //Resize image depend upon your need
            //For give the size to image
            //jpg.ScaleToFit(2500, 500);

            //If you want to choose image as background then,

            jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

            //If you want to give absolute/specified fix position to image.
            jpg.SetAbsolutePosition(15, 40);
            

        }
Exemple #32
0
 public void AddLogo(PdfDocument doc, int x, int y)
 {
     L= Image.GetInstance(_path);
     L.SetAbsolutePosition(x,y);
     doc.AddElement(L);
     doc.Flush();
 }