Exemplo n.º 1
0
 private byte[] RetornarArrayBytesTemplate(List <DadosImagem> imagens)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         PdfStamper pdfStamper = new PdfStamper(new PdfReader(this.Template.Caminho), (Stream)memoryStream);
         AcroFields acroFields = pdfStamper.AcroFields;
         foreach (KeyValuePair <string, string> parametro in this.Template.Parametros)
         {
             acroFields.SetField(parametro.Key, parametro.Value);
         }
         foreach (DadosImagem imagen in imagens)
         {
             if (imagen.Barcode)
             {
                 Barcode128 barcode128 = new Barcode128();
                 barcode128.Code = imagen.AtributosImagem;
                 iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(barcode128.CreateDrawingImage(Color.Black, Color.White), BaseColor.White);
                 pdfStamper.GetOverContent(1).AddImage(instance, (float)Convert.ToInt32((double)instance.Width * 0.98), 0.0f, 0.0f, instance.Height, 25f, 445f);
             }
             else
             {
                 iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(imagen.Imagem, BaseColor.White);
                 pdfStamper.GetOverContent(1).AddImage(instance, instance.Width, 0.0f, 0.0f, instance.Height, (float)imagen.PosicaoVertical, (float)imagen.PosicaoHorizontal);
             }
         }
         pdfStamper.FormFlattening = true;
         pdfStamper.Close();
         return(memoryStream.ToArray());
     }
 }
Exemplo n.º 2
0
// ---------------------------------------------------------------------------

        /**
         * Shows the stream passed to the server with POST
         */
        protected void DoPost(byte[] pdf, Stream stream)
        {
            using (Stream s = WebContext.Request.InputStream) {
                // Create a reader that interprets the Request's input stream
                FdfReader fdf = new FdfReader(s);
                // We get a resource from our web app
                PdfReader reader = new PdfReader(pdf);
                // Now we create the PDF
                using (PdfStamper stamper = new PdfStamper(reader, stream)) {
                    // We alter the fields of the existing PDF
                    AcroFields fields = stamper.AcroFields;
                    fields.SetFields(fdf);
                    stamper.FormFlattening = true;
                    // Gets the image from the FDF file
                    try {
                        Image img = Image.GetInstance(fdf.GetAttachedFile("image"));
                        img.ScaleToFit(100, 100);
                        img.SetAbsolutePosition(90, 590);
                        stamper.GetOverContent(1).AddImage(img);
                    }
                    catch {
                        ColumnText.ShowTextAligned(
                            stamper.GetOverContent(1),
                            Element.ALIGN_LEFT,
                            new Phrase("No image posted!"),
                            90, 660, 0
                            );
                    }
                }
            }
        }
Exemplo n.º 3
0
        public void Format(string input, string output)
        {
            var            LogoPath   = formatterSettings.LogoPath;
            var            BorderPath = formatterSettings.BorderPath;
            PdfContentByte pdfContent;

            PdfReader  pdfReader  = new PdfReader(input);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(output, FileMode.Create));

            int numberOfPages = pdfReader.NumberOfPages;

            for (int i = 0; i < numberOfPages; i++)
            {
                Image logo = Image.GetInstance(LogoPath);
                logo.SetAbsolutePosition(410, 745);
                pdfContent = pdfStamper.GetOverContent(i + 1);
                pdfContent.AddImage(logo);
            }

            Image border = Image.GetInstance(BorderPath);

            border.ScaleAbsoluteHeight(105f);
            border.ScaleAbsoluteWidth(557);
            border.SetAbsolutePosition(26, 515);

            pdfContent = pdfStamper.GetOverContent(1);
            pdfContent.AddImage(border);

            pdfStamper.Close();
        }
Exemplo n.º 4
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);
            }
        }
Exemplo n.º 5
0
        //print on page 5
        private void pdfWrite_Form6(ref PdfStamper stamper, ref PdfReader reader)
        {
            int            pageNo = 5; //page = 5 is  ;Asset and Liabilities form
            PdfContentByte canvas = stamper.GetOverContent(pageNo);

            //'''''''''''''''''''''print for "Name of Assessee and TIN number"

            WriteStringOnPdf(ref canvas, ref reader, pageNo, Form1_Personal_info.pdfInputs[0], 180, 85); //print "Name of Assessee"

            float  tempX = 104;                                                                          //set "TIN" number positon x=104
            float  tempY = 104;                                                                          //set "TIN" number positon  y = 104
            string s     = Form1_Personal_info.pdfInputs[3];                                             //get "TIN" as a string

            //print "TIN" above the "Expense form"
            for (int i = 0; i < s.Length; i++)
            {
                if (i == 3 || i == 6) //checking to jump additionally
                {
                    tempX += 14;      // jump with difference of x=16 to right hand side box
                }

                WriteStringOnPdf(ref canvas, ref reader, pageNo, s[i] + "", tempX, tempY); //print each of TIN number one by one
                tempX += 13;                                                               // jump with difference of x=16 to right hand side box
            }

            //..........................

            Form6_HelperFunction1(ref canvas, ref reader); //print on page 5;Asset and Liabilities form

            pageNo = 6;                                    //page = 6 is  ;Asset and Liabilities form
            canvas = stamper.GetOverContent(pageNo);
            Form6_HelperFunction2(ref canvas, ref reader);
        }
Exemplo n.º 6
0
        public static MemoryStream GenerateSingleBadge(Guid Id, UnitOfWork unitOfWork)
        {
            Setting      setting = GetSetting(unitOfWork);
            Registration reg     = unitOfWork.RegistrationRepository.GetByID(Id);

            string pdfPath = setting.WebLocation + "Storage\\Pdf\\Badge.pdf";

            PdfReader    pdfReader = null;
            MemoryStream memoryStreamPdfStamper = null;
            PdfStamper   pdfStamper             = null;
            AcroFields   pdfFormFields          = null;

            pdfReader = new PdfReader(pdfPath);

            memoryStreamPdfStamper = new MemoryStream();
            pdfStamper             = new PdfStamper(pdfReader, memoryStreamPdfStamper);
            pdfFormFields          = pdfStamper.AcroFields;

            pdfFormFields.SetField("name", reg.Name);


            // Barcode
            MemoryStream memoryStream = GenerateQrcode(reg.SerialNo, 119, 119);

            iTextSharp.text.Image img            = null;
            PdfContentByte        pdfContentByte = null;

            img = iTextSharp.text.Image.GetInstance(memoryStream);
            img.ScaleToFit(190, 30);
            pdfContentByte = pdfStamper.GetOverContent(1);
            img.SetAbsolutePosition(95f, 59f);

            pdfContentByte.AddImage(img);

            memoryStream = new MemoryStream(reg.Image);
            img          = iTextSharp.text.Image.GetInstance(memoryStream);
            img.ScaleToFit(290, 120);
            pdfContentByte = pdfStamper.GetOverContent(1);
            img.SetAbsolutePosition(70f, 140f);

            pdfContentByte.AddImage(img);

            pdfStamper.FormFlattening     = true;
            pdfStamper.Writer.CloseStream = false;
            pdfStamper.Close();

            memoryStreamPdfStamper.Flush();
            memoryStreamPdfStamper.Seek(0, SeekOrigin.Begin);

            //MemoryStream docstream = CreatePdfDoc(memoryStreamPdfStamper);
            //memoryStreamPdfStamper.Dispose();

            //docstream.Position = 0;
            //return docstream;

            //memoryStreamPdfStamper.Position = 0;
            return(memoryStreamPdfStamper);
        }
Exemplo n.º 7
0
        private void ReplaceText(string textToBeSearched, string textToAdd, string outputFilePath, string inputFilePath)
        {
            try
            {
                using (Stream inputPdfStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (Stream outputPdfStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                        using (Stream outputPdfStream2 = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            //Opens the unmodified PDF for reading
                            PdfReader reader = new PdfReader(inputPdfStream);
                            //Creates a stamper to put an image on the original pdf
                            PdfStamper stamper = new PdfStamper(reader, outputPdfStream); //{ FormFlattening = true, FreeTextFlattening = true };
                            for (var i = 1; i <= reader.NumberOfPages; i++)
                            {
                                var tt = new MyLocationTextExtractionStrategy(textToBeSearched);
                                var ex = PdfTextExtractor.GetTextFromPage(reader, i, tt); // ex will be holding the text, although we just need the rectangles [RectAndText class objects]
                                foreach (var p in tt.myPoints)
                                {
                                    //Creates an image that is the size i need to hide the text i'm interested in removing
                                    Bitmap transparentBitmap = new Bitmap((int)p.Rect.Width, (int)p.Rect.Height);
                                    transparentBitmap.MakeTransparent();
                                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(transparentBitmap, new BaseColor(255, 255, 255));
                                    //Sets the position that the image needs to be placed (ie the location of the text to be removed)
                                    image.SetAbsolutePosition(p.Rect.Left, (p.Rect.Top - 15));
                                    //Adds the image to the output pdf
                                    stamper.GetOverContent(i).AddImage(image, true); // i stands for the page no.

                                    PdfContentByte cb = stamper.GetOverContent(i);

                                    // 中文自型設定------------
                                    //int fontStyle = 1; // 設定為粗體
                                    string   fontPath = "c:\\windows\\fonts\\KAIU.TTF";
                                    BaseFont bf       = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                                    //----------------------------------

                                    // select the font properties
                                    //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                                    cb.SetColorFill(BaseColor.BLACK);
                                    cb.SetFontAndSize(bf, 14);

                                    // write the text in the pdf content
                                    cb.BeginText();
                                    // put the alignment and coordinates here
                                    cb.ShowTextAligned(1, textToAdd, p.Rect.Left + 14, p.Rect.Top - 10, 0);
                                    cb.EndText();
                                }
                            }
                            //Creates the first copy of the outputted pdf
                            stamper.Close();
                        }
            }
            catch (Exception ex)
            {
            }
        }
 public void SetImage(string fieldName, byte[] image)
 {
     if (image == null)
     {
         return;
     }
     float[] pos = stamper.AcroFields.GetFieldPositions(fieldName);
     for (int i = 0; i < pos.Length - 4; i += 5)
     {
         iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image);
         img.ScaleToFit(Math.Abs(pos[i + 1] - pos[i + 3]), Math.Abs(pos[i + 2] - pos[i + 4]));
         img.SetAbsolutePosition(pos[i + 1] + Math.Abs(pos[i + 1] - pos[i + 3]) / 2 - img.ScaledWidth / 2, pos[i + 2] + Math.Abs(pos[i + 2] - pos[i + 4]) / 2 - img.ScaledHeight / 2);
         stamper.GetOverContent((int)pos[i]).AddImage(img);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// 添加链接到PDF
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="toPath"></param>
        /// <param name="url"></param>
        /// <param name="urlName"></param>
        /// <param name="absoluteX"></param>
        /// <param name="absoluteY"></param>
        /// <param name="fitWidth"></param>
        /// <param name="fitHeight"></param>
        public static void AddLink(string filePath, string toPath, string url, string urlName, float absoluteX, float absoluteY, float fitWidth, float fitHeight)
        {
            PdfReader  reader = new PdfReader(filePath);
            FileStream fs     = new FileStream(toPath, FileMode.Create);
            PdfStamper stamp  = null;

            try
            {
                stamp = new PdfStamper(reader, fs);
                int    i = 0;
                int    n = reader.NumberOfPages;
                Anchor a = new Anchor(urlName, FontFactory.GetFont("Helvetica", 12f, 4, new iTextSharp.text.Color(0, 0, 0xff)));
                a.Reference = url;
                new PdfAction(new Uri(url));
                while (i < n)
                {
                    i++;
                    reader.GetPageSizeWithRotation(i);
                    stamp.GetOverContent(i);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fs.Dispose();
                fs.Close();
            }
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 转化PDF加图片水印
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="toPath"></param>
        /// <param name="imgpath"></param>
        /// <param name="absoluteX"></param>
        /// <param name="absoluteY"></param>
        /// <param name="fitWidth"></param>
        /// <param name="fitHeight"></param>
        /// <param name="url"></param>
        public static void ConvertPDFToPDFByImg(string filePath, string toPath, System.Drawing.Image imgpath, float absoluteX, float absoluteY, string url)
        {
            PdfReader  reader = new PdfReader(filePath);
            FileStream fs     = new FileStream(toPath, FileMode.Create);
            PdfStamper stamp  = null;

            try
            {
                stamp = new PdfStamper(reader, fs);
                int i = 0;
                while (reader.NumberOfPages > i)
                {
                    i++;
                    Image     mm       = Image.GetInstance(imgpath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Rectangle pageSize = reader.GetPageSizeWithRotation(i);
                    mm.SetAbsolutePosition(absoluteX, absoluteY);
                    mm.ScaleAbsolute((float)imgpath.Width, (float)imgpath.Height);
                    mm.Annotation = new Annotation(0f, 0f, 0f, 0f, url);
                    stamp.GetOverContent(i).AddImage(mm);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fs.Dispose();
                fs.Close();
            }
        }
Exemplo n.º 12
0
        // todo : Remove unsed method
        public static byte[] To_PDF(string pdfPath, string barCodeImagePath)
        {
            var pdfWithAttachmentBytes = new byte[] { };


            var pathToSavePDf = AppDomain.CurrentDomain.BaseDirectory + "Document\\PDFBarCodeAttached.pdf";

            using (Stream inputPdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream inputImageStream = new FileStream(barCodeImagePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (Stream outputPdfStream = new FileStream(pathToSavePDf, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        var reader         = new PdfReader(inputPdfStream);
                        var stamper        = new PdfStamper(reader, outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(1);

                        var jpg = Image.GetInstance(inputImageStream);
                        jpg.ScaleToFit(140f, 120f);
                        jpg.SpacingBefore = 10f;
                        jpg.SpacingAfter  = 1f;
                        jpg.Alignment     = Element.ALIGN_LEFT;
                        jpg.SetAbsolutePosition(100, 100);

                        pdfContentByte.AddImage(jpg);
                        stamper.Close();

                        pdfWithAttachmentBytes = File.ReadAllBytes(pathToSavePDf);
                    }

            return(pdfWithAttachmentBytes);
        }
Exemplo n.º 13
0
        public static Stream AddPdfWaterMark(string sourceFile, string stringToWriteToPdf)
        {
            PdfReader  reader     = null;
            PdfStamper pdfStamper = null;

            try
            {
                reader = new PdfReader(System.IO.File.ReadAllBytes(sourceFile));
                iTextSharp.text.Rectangle psize = reader.GetPageSize(1);

                float     width  = psize.Width;
                float     height = psize.Height;
                int       j      = stringToWriteToPdf.Length;
                PdfGState gs     = new PdfGState();
                gs.FillOpacity = 0.15f;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int rise  = 100;
                    int total = reader.NumberOfPages + 1;
                    pdfStamper = new PdfStamper(reader, memoryStream);
                    for (int i = 1; i < total; i++)
                    {
                        PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);
                        BaseFont       baseFont        = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                        pdfPageContents.BeginText();
                        pdfPageContents.SetFontAndSize(baseFont, 40);
                        pdfPageContents.SetRGBColorFill(255, 0, 0);
                        pdfPageContents.SetColorFill(iTextSharp.text.BaseColor.GRAY);
                        pdfPageContents.SetFontAndSize(font, 60);
                        pdfPageContents.SetTextRise(rise);
                        pdfPageContents.SetGState(gs);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, stringToWriteToPdf, 300, 500, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, stringToWriteToPdf, 400, 400, 45);
                        pdfPageContents.ShowTextAligned(iTextSharp.text.Element.ALIGN_RIGHT, stringToWriteToPdf, 500, 300, 45);
                        pdfPageContents.EndText();
                    }
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();
                    return(new System.IO.MemoryStream(memoryStream.ToArray()));
                }
            }
            catch (Exception ex)
            {
                WriteLog(string.Format("{0},{1}", ex.Message, ex.StackTrace));
                return(new System.IO.MemoryStream(File.ReadAllBytes(sourceFile)));
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Exemplo n.º 14
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create the reader
            PdfReader reader = new PdfReader(src);
            int       n      = reader.NumberOfPages;

            using (MemoryStream ms = new MemoryStream())
            {
                // Create the stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Make a list with all the possible actions
                    actions = new List <PdfAction>();
                    PdfDestination d;
                    for (int i = 0; i < n;)
                    {
                        d = new PdfDestination(PdfDestination.FIT);
                        actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer));
                    }
                    // Add a navigation table to every page
                    PdfContentByte canvas;
                    for (int i = 0; i < n;)
                    {
                        canvas = stamper.GetOverContent(++i);
                        CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas);
                    }
                }
                return(ms.ToArray());
            }
        }
        protected 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);
        }
Exemplo n.º 16
0
        public string SignFile(byte[] fileToSign, int documentID, int pageNumber, byte[] userSignature, float x, float y)
        {
            var stream = new MemoryStream(fileToSign);

            PdfReader  pdfReader  = new PdfReader(stream);
            var        newFile    = new MemoryStream();
            PdfStamper pdfStamper = new PdfStamper(pdfReader, newFile);

            //Image image = Image.GetInstance(Path.Combine(pathToResources, "Matt Signature.png"));
            Image image = Image.GetInstance(userSignature.ToArray());

            image.ScaleAbsolute(150f, 75f);
            PdfContentByte content = pdfStamper.GetOverContent(pageNumber);

            //image.SetAbsolutePosition(pdfReader.GetPageSize(1).Width * x, pdfReader.GetPageSize(1).Height * y);
            //image.SetAbsolutePosition(content.co, 0f);
            image.SetAbsolutePosition(PageSize.LETTER.Width * (x * .9f), PageSize.LETTER.Height * (1 - y));
            //image.SetAbsolutePosition(PageSize.LETTER.Width - image.ScaledWidth, 0);

            content.AddImage(image);

            pdfStamper.Close();
            var stamp  = $"http://signme/Documents/{documentID}";
            var final  = AddWaterMark(newFile.ToArray(), $"Signed {DateTime.Now.ToString("d")} ");
            var final2 = ApplyVerificationStamp2(final.ToArray(), stamp);

            return(Convert.ToBase64String(final2.ToArray()));
        }
Exemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pdfPath"></param>
        /// <param name="imagePath"></param>
        /// <param name="info"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private static void AddImageToPdf(string pdfPath, string imagePath, float x, float y)
        {
            if (string.IsNullOrWhiteSpace(pdfPath) || string.IsNullOrWhiteSpace(imagePath))
            {
                throw new ArgumentException();
            }
            if (!File.Exists(pdfPath) || !File.Exists(imagePath))
            {
                throw new FileNotFoundException();
            }
            var srcPath2 = "result.pdf";

            using (Stream inputPdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.ReadWrite))
                using (Stream inputImageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                    using (Stream outputPdfStream = new FileStream(srcPath2, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        var reader  = new PdfReader(inputPdfStream);
                        var stamper = new PdfStamper(reader, outputPdfStream);
                        stamper.InsertPage(reader.NumberOfPages, PageSize.A4);
                        var pdfConcat      = new PdfConcatenate(outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(reader.NumberOfPages);

                        Image image = Image.GetInstance(inputImageStream);
                        image.SetAbsolutePosition(x, y);
                        image.ScaleToFit(new Rectangle(100, 100));
                        pdfContentByte.AddImage(image);

                        Paragraph elements = new Paragraph();
                        //pdfContentByte.AddOutline()
                        stamper.Close();
                    }
            //允许抛出异常
            File.Copy(srcPath2, pdfPath, true);
        }
Exemplo n.º 18
0
        public byte[] IncrustarFirma(string pdf, string firma, int page, int posX, int posY)
        {
            byte[] __pdfContent   = File.ReadAllBytes(pdf);
            byte[] __imageContent = File.ReadAllBytes(firma);

            using (Stream inputPdfStream = new MemoryStream(__pdfContent)){
                using (Stream inputImageStream = new MemoryStream(__imageContent)){
                    using (MemoryStream ms = new MemoryStream()) {
                        var reader = new PdfReader(inputPdfStream);
                        using (PdfStamper stamper = new PdfStamper(reader, ms, '\0', true)) {
                            var   pdfContentByte = stamper.GetOverContent(page);
                            Image image          = Image.GetInstance(inputImageStream);
                            image.SetAbsolutePosition(posX, posY);
                            image.BorderWidth = 0;
                            image.Alignment   = Element.ALIGN_RIGHT;
                            float percentage2 = 0.0f;
                            percentage2 = 150 / image.Width;
                            image.ScalePercent(percentage2 * 100);
                            pdfContentByte.AddImage(image);
                        }
                        return(ms.ToArray());
                    }
                }
            }
        }
Exemplo n.º 19
0
        private static void InsertImageToPdf(string inputPdfPath, string outputPdfPath, string imagePathToInsert, int destPageIndex, Rectangle destinationRect, string fullpageLabel)
        {
            using (Stream inputImageStream = new FileStream(imagePathToInsert, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(outputPdfPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    using (var pdfReader = new PdfReader(inputPdfPath))
                        using (var stamper = new PdfStamper(pdfReader, outputPdfStream))
                        {
                            var pdfContentByte = stamper.GetOverContent(destPageIndex);

                            // Insert Image
                            Image image = Image.GetInstance(inputImageStream);
                            image.ScaleToFit(destinationRect);
                            image.SetAbsolutePosition(destinationRect.GetLeft(0), destinationRect.GetTop(0) - image.PlainHeight);
                            pdfContentByte.AddImage(image);

                            // Change Page Number
                            var af    = stamper.AcroFields;
                            var field = af.Fields.SingleOrDefault(kv => kv.Value.GetPage(0) == destPageIndex && kv.Key.Length == 2 && kv.Key[0] == 'L');

                            if (field.Key == null)
                            {
                                throw new Exception("No page number found on the page");
                            }

                            af.SetField(field.Key, fullpageLabel);

                            stamper.Close();
                        }
        }
        /// <summary>
        ///   Sets the fields in the pdf stamper with the given object data.
        ///   Based on the framework, it's easier to use an anonymous-object to fill the pdf.
        /// </summary>
        /// <param name="pdfStamper">The pdf stamper to use.</param>
        /// <param name="data">The data to set.</param>
        public static void SetFields(this PdfStamper pdfStamper, object data)
        {
            if (pdfStamper.IsXfaCompliant())
            {
                pdfStamper.AcroFields.Xfa.FillXfaForm(data.ToXfaCompliantXml());
            }
            else
            {
                foreach (var fieldName in pdfStamper.GetFieldNames())
                {
                    var valToSet = data.GetPropertyValue <object>(fieldName);

                    var isImageData = valToSet.IsNotNull() && valToSet.GetType() == typeof(byte[]);
                    if (isImageData && pdfStamper.GetFieldPosition(fieldName, out var fieldPos))
                    {
                        var image = Image.GetInstance((byte[])valToSet);
                        pdfStamper.GetOverContent(fieldPos.page).AddImage(image.SetImageMetrics(fieldPos));
                    }
                    else
                    {
                        pdfStamper.AcroFields.SetField(fieldName, valToSet.ToStringSafe());
                    }
                }
            }
        }
Exemplo n.º 21
0
        public static bool InsertSignatureIntoDocument(string imagePath, string pdfPath)
        {
            string[] arrImage        = imagePath.Split("/");
            string[] arrPdf          = pdfPath.Split("/");
            string   imagePathStream = Path.Combine(Const.FILE_UPLOAD_DIGITAL_SIGNATURE, arrImage[arrImage.Length - 1]);
            string   pdfPathStream   = Path.Combine(Const.FILE_UPLOAD_DIR, arrPdf[arrPdf.Length - 2], arrPdf[arrPdf.Length - 1]);

            using (Stream inputPdfStream = new FileStream(pdfPathStream, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream inputImageStream = new FileStream(imagePathStream, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    try
                    {
                        var       reader   = new PdfReader(inputPdfStream);
                        Rectangle pageSize = reader.GetPageSizeWithRotation(1);

                        // xóa file đã tồn tại trước đó
                        //File.Delete(pdfPathStream);

                        using (Stream outputPdfStream = new FileStream(pdfPathStream, FileMode.Open, FileAccess.Write, FileShare.None))
                        {
                            var   stamper        = new PdfStamper(reader, outputPdfStream);
                            var   pdfContentByte = stamper.GetOverContent(1);
                            Image image          = Image.GetInstance(inputImageStream);
                            image.SetAbsolutePosition(50, pageSize.Height - image.Height - 25);
                            pdfContentByte.AddImage(image);
                            stamper.Close();
                        }
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
        }
Exemplo n.º 22
0
        public void Verify_NamedActions_CanBeCreated()
        {
            var pdfFilePath = TestUtils.GetOutputFileName();
            var stream      = new FileStream(pdfFilePath, FileMode.Create);

            // Create a reader
            var pdfFile = createSamplePdfFile();
            var reader  = new PdfReader(pdfFile);

            // Create a stamper
            var stamper = new PdfStamper(reader, stream);

            var table = createTableWithNamedActions();

            // Add the table to each page
            for (var i = 0; i < reader.NumberOfPages;)
            {
                var canvas = stamper.GetOverContent(++i);
                table.WriteSelectedRows(0, -1, 696, 36, canvas);
            }

            reader.Close();
            stamper.Close();
            stream.Dispose();

            TestUtils.VerifyPdfFileIsReadable(pdfFilePath);
        }
Exemplo n.º 23
0
        private void ParseAndHighlight(String input, String output, bool singleCharacters)
        {
            PdfReader  reader  = new PdfReader(input);
            FileStream fos     = new FileStream(output, FileMode.Create);
            PdfStamper stamper = new PdfStamper(reader, fos);

            PdfReaderContentParser parser           = new PdfReaderContentParser(reader);
            MyRenderListener       myRenderListener = singleCharacters ? new MyCharacterRenderListener() : new MyRenderListener();

            for (int pageNum = 1; pageNum <= reader.NumberOfPages; pageNum++)
            {
                List <Rectangle> rectangles = parser.ProcessContent(pageNum, myRenderListener).GetRectangles();
                PdfContentByte   canvas     = stamper.GetOverContent(pageNum);
                canvas.SetLineWidth(0.5f);
                canvas.SetColorStroke(BaseColor.RED);
                foreach (Rectangle rectangle in rectangles)
                {
                    canvas.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                    canvas.Stroke();
                }
            }
            stamper.Close();
            fos.Close();
            reader.Close();
        }
Exemplo n.º 24
0
        public static void GeneratePODForm(string templateFormsPath, string podFilePath, string receivedBy, string receivingTime, string signature)
        {
            PdfReader reader = new PdfReader(templateFormsPath);

            //select three pages from the original document
            reader.SelectPages("1-3");
            //create PdfStamper object to write to get the pages from reader
            PdfStamper stamper = new PdfStamper(reader, new FileStream(podFilePath, FileMode.Create));

            Rectangle pagesize = reader.GetPageSize(1);

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

            //add content to the page using ColumnText
            ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivedBy), pagesize.Left + 320, pagesize.Bottom + 90, 0);
            ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivingTime), pagesize.Left + 400, pagesize.Bottom + 60, 0);

            // PdfContentByte from stamper to add content to the pages under the original content
            //add image from a file
            iTextSharp.text.Image img = new Jpeg(imageToByteArray(System.Drawing.Image.FromFile(signature)));
            //add the image under the original content
            img.SetAbsolutePosition(pagesize.Left + 380, pagesize.Bottom + 10);
            pbunder.AddImage(img);

            //pbunder.AddImage(img, img.Width / 2, 0, 0, img.Height / 2, 0, 0);

            //close the stamper
            stamper.Close();
        }
Exemplo n.º 25
0
        protected void AddPageNumberAndLogo(string url)
        {
            byte[]     bytes = File.ReadAllBytes(url);
            AcroFields pdfFormFields;
            string     imagenTanner = "LogoTCB.PNG";
            string     imagenPath   = Path.Combine(@"img/", imagenTanner);

            Font blackFont = FontFactory.GetFont("Arial", 20.5f, Font.NORMAL, BaseColor.BLACK);

            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader reader = new PdfReader(bytes);
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    pdfFormFields = stamper.AcroFields;
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase("Pagina " + i.ToString() + " de " + pages, blackFont), 230f, 15f, 0);

                        Image instanceImg = Image.GetInstance(imagenPath);
                        instanceImg.ScalePercent(12);
                        PdfContentByte overContent = stamper.GetOverContent(i);
                        instanceImg.SetAbsolutePosition(3160f, 2295f);
                        instanceImg.Alignment = Image.ALIGN_RIGHT;
                        overContent.AddImage(instanceImg);
                    }
                }
                bytes = stream.ToArray();
            }
            File.WriteAllBytes(url, bytes);
        }
Exemplo n.º 26
0
 public void Run()
 {
     try {
         PdfReader reader =
             new PdfReader(File.Open(TEST_RESOURCES_PATH + "test.pdf", FileMode.Open, FileAccess.Read,
                                     FileShare.Read));
         PdfStamper stamper = new PdfStamper(reader,
                                             new FileStream(TARGET_PATH + "out" + threadNumber + ".pdf", FileMode.Create));
         PdfContentByte cb = stamper.GetOverContent(1);
         cb.BeginText();
         BaseFont font = BaseFont.CreateFont(TEST_RESOURCES_PATH + "FreeSans.ttf",
                                             threadNumber % 2 == 0 ? BaseFont.IDENTITY_H : BaseFont.WINANSI, BaseFont.EMBEDDED);
         cb.SetFontAndSize(font, 12);
         cb.MoveText(30, 600);
         cb.ShowText("`1234567890-=qwertyuiop[]asdfghjkl;'\\zxcvbnm,./");
         cb.EndText();
         stamper.Close();
         reader.Close();
     }
     catch (Exception exc) {
         RegisterException(threadNumber, exc);
     }
     finally {
         latch.Decrement();
     }
 }
Exemplo n.º 27
0
        static void manipulatePdf(string src, string dest, string imageFile)
        {
            PdfReader reader = new PdfReader(src);

            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write));

            //GetInstance(System.Drawing.Image image, BaseColor color, bool forceBW) {

            System.Drawing.Image  img   = System.Drawing.Image.FromFile(imageFile);
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE, false);

            PdfImage stream = new PdfImage(image, "", null);

            stream.Put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));

            PdfIndirectObject reference = stamper.Writer.AddToBody(stream);

            image.DirectReference = reference.IndirectReference;
            image.ScaleAbsolute(133, 100);
            iTextSharp.text.Rectangle pagesize = reader.GetPageSizeWithRotation(1);
            image.SetAbsolutePosition(0, pagesize.Height - 100);
            //image.ScaleAbsolute(new iTextSharp.text.Rectangle(
            PdfContentByte over = stamper.GetOverContent(1);

            over.AddImage(image);
            stamper.Close();
            reader.Close();
        }
Exemplo n.º 28
0
        public static void LabelAcroFields(string fileName, string outputFileName, List <AcroFieldProperties> acroFieldsProps)
        {
            PdfReader  reader = new PdfReader(fileName);
            FileStream output = new FileStream(outputFileName, FileMode.Create, FileAccess.Write);
            PdfStamper stamp  = new PdfStamper(reader, output);

            foreach (var acroFieldProp in acroFieldsProps)
            {
                if (acroFieldProp.IsCheckBox() || acroFieldProp.IsRadioButton())
                {
                    var   canvas = stamp.GetOverContent(acroFieldProp.PageNumber);
                    float height = acroFieldProp.TopPos - acroFieldProp.BottomPos;

                    canvas.WriteContent(CreateAcroFieldNameTable(acroFieldProp), acroFieldProp.LeftPos, acroFieldProp.BottomPos + 1.5f * height);
                }
                else
                {
                    stamp.AcroFields.SetFieldProperty(acroFieldProp.Name, "textfont", frutigerLight5.BaseFont, null);
                    stamp.AcroFields.SetFieldProperty(acroFieldProp.Name, "textcolor", BaseColor.RED, null);
                    stamp.AcroFields.SetFieldProperty(acroFieldProp.Name, "textsize", 5f, null);
                    stamp.AcroFields.SetField(acroFieldProp.Name, acroFieldProp.Name);
                }
            }

            stamp.Close();
        }
        public static void markFields(string file)
        {
            string     outfile = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file) + "-marked" + Path.GetExtension(file));
            FileStream temp    = new FileStream(outfile, FileMode.CreateNew);

            using (PdfReader sheet = new PdfReader(file))
            {
                sheet.RemoveUsageRights();
                using (PdfStamper p = new PdfStamper(sheet, temp))
                {
                    foreach (string field in sheet.AcroFields.Fields.Keys)
                    {
                        foreach (AcroFields.FieldPosition pos in p.AcroFields.GetFieldPositions(field))
                        {
                            Rectangle      pageSize        = sheet.GetPageSizeWithRotation(pos.page);
                            PdfContentByte pdfPageContents = p.GetOverContent(pos.page);
                            pdfPageContents.BeginText();
                            BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                            pdfPageContents.SetFontAndSize(baseFont, 6);
                            pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, field, pos.position.Left + pos.position.Width / 2, pos.position.Top - pos.position.Height / 2, 0);
                            pdfPageContents.EndText();
                        }
                    }
                    p.FormFlattening = true;
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Fills out and flattens a form with the name, company and country.
        /// </summary>
        /// <param name="src"> the path to the original form </param>
        /// <param name="dest"> the path to the filled out form </param>
        public void ManipulatePdf(String src, String dest)
        {
            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            int        n       = reader.NumberOfPages;
            Rectangle  pagesize;

            for (int i = 1; i <= n; i++)
            {
                PdfContentByte over = stamper.GetOverContent(i);
                pagesize = reader.GetPageSize(i);
                float     x  = (pagesize.Left + pagesize.Right) / 2;
                float     y  = (pagesize.Bottom + pagesize.Top) / 2;
                PdfGState gs = new PdfGState();
                gs.FillOpacity = 0.3f;
                over.SaveState();
                over.SetGState(gs);
                over.SetRGBColorFill(200, 200, 0);
                ColumnText.ShowTextAligned(over, Element.ALIGN_CENTER,
                                           new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
                                           x, y, 45);
                over.RestoreState();
            }
            stamper.Close();
            reader.Close();
        }