Exemplo n.º 1
0
        /// <summary>
        /// Methode um Nummern und Projektnamen auf Pdf zu drucken
        /// </summary>
        ///
        /// Erstellt von Adrian Glasnek

        public void GetPageNumber(SaveFileDialog save, int pageNumberBottomPosition)
        {
            try
            {
                byte[] bytes     = File.ReadAllBytes(save.FileName);
                Font   BlackFont = FontFactory.GetFont("Arial", 9, Font.BOLD, BaseColor.BLACK);
                using (MemoryStream stream = new MemoryStream())
                {
                    PdfReader reader = new PdfReader(bytes);
                    using (PdfStamper stamper = new PdfStamper(reader, stream))
                    {
                        int pages = reader.NumberOfPages;
                        //Schleife um zu gewährleisten das jede Seite des Dokuments berücksichtigt wird
                        for (int i = 1; i <= pages; i++)
                        {
                            //Seitenzahl
                            ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), BlackFont), pageNumberBottomPosition, 15f, 0);
                            //Projekt Name
                            ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(Project.Name.ToString(), BlackFont), 400, 15f, 0);
                        }
                    }
                    bytes = stream.ToArray();
                }
                File.WriteAllBytes(save.FileName, bytes);
            }
            catch (Exception) { throw new Exception("Bitte schließen Sie das geöffnete Pdf"); }
        }
Exemplo n.º 2
0
        public static byte[] AddPageNumber(Document document, byte[] bytes, string text)
        {
            float x = document.Right;
            float y = document.Bottom + document.RightMargin - document.BottomMargin;

            //Font blackFont = FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.BLACK);
            using (var stream = new MemoryStream())
            {
                var reader = new PdfReader(bytes);
                using (var stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_LEFT, new Phrase("Copyright © 2015 TheRestaurantExpert.com. Generated by Smart System Pro All Rights Reserved.", subTitle), document.Left, y, 0);
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase("Page " + i, subTitle), x, y, 0);

                        if (i > 1)
                        {
                            ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_LEFT, new Phrase(text, subTitle), document.Left, document.PageSize.Height - 30, 0);
                        }
                    }
                }
                bytes = stream.ToArray();
            }
            return(bytes);
        }
Exemplo n.º 3
0
 private static void CreateOnBottom(PdfStamper stamper, PageNumber pagingOptions, int currrent, Rectangle pageBox,
                                    float textWidth, Phrase textPhrase)
 {
     if (pagingOptions.Alignment == Alignment.Center)
     {
         var location = (pageBox.Height + textWidth) / 2;
         ColumnText.ShowTextAligned(stamper.GetUnderContent(currrent), Element.ALIGN_CENTER, textPhrase, location, 10f,
                                    0,
                                    pagingOptions.Direction == Direction.RightToLeft
                 ? PdfWriter.RUN_DIRECTION_RTL
                 : PdfWriter.RUN_DIRECTION_DEFAULT, 1);
     }
     else if (pagingOptions.Alignment == Alignment.Right)
     {
         var location = pageBox.Height - textWidth - 15;
         ColumnText.ShowTextAligned(stamper.GetUnderContent(currrent), Element.ALIGN_RIGHT, textPhrase, location, 10f, 0,
                                    pagingOptions.Direction == Direction.RightToLeft
                 ? PdfWriter.RUN_DIRECTION_RTL
                 : PdfWriter.RUN_DIRECTION_DEFAULT, 1);
     }
     else if (pagingOptions.Alignment == Alignment.Left)
     {
         var location = textWidth + 15;
         ColumnText.ShowTextAligned(stamper.GetUnderContent(currrent), Element.ALIGN_LEFT, textPhrase, location, 10f, 0,
                                    pagingOptions.Direction == Direction.RightToLeft
                 ? PdfWriter.RUN_DIRECTION_RTL
                 : PdfWriter.RUN_DIRECTION_DEFAULT, 1);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Edit Pdf file with Data Source from Data Table Source
        /// </summary>
        /// <param name="_PathFile"></param>
        /// <param name="_dtbSource"></param>
        public static void EditMultiPdf(string _PathFile, System.Data.DataTable _dtbSource)
        {
            try
            {
                byte[] bytes = File.ReadAllBytes(_PathFile);

                #region 20161206 - BotJava - Edit font
                //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

                string arialuniTff = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                                                            "ARIALUNI.TTF");
                BaseFont bf = BaseFont.CreateFont(arialuniTff, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                iTextSharp.text.Font blackFont = new iTextSharp.text.Font(bf, 12);
                #endregion

                using (MemoryStream stream = new MemoryStream())
                {
                    PdfReader reader = new PdfReader(bytes);
                    using (PdfStamper stamper = new PdfStamper(reader, stream))
                    {
                        int _tempk = 0;
                        int pages  = reader.NumberOfPages;
                        for (int i = 1; i <= pages; i++)
                        {
                            #region 20161206 - BotJava - Insert data for first 注文書
                            // Insert 棚番号
                            ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase(_dtbSource.Rows[i - 1 + _tempk]["棚番号"].ToString(), blackFont), 500f, 575f, 0);
                            // Insert 出庫番号
                            ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase(_dtbSource.Rows[i - 1 + _tempk]["組込番号"].ToString(), blackFont), 430f, 510f, 0);

                            #endregion

                            #region 20161206 - BotJava - Insert data for second 注文書
                            if ((i + _tempk) < _dtbSource.Rows.Count)
                            {
                                //Insert 棚番号
                                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase(_dtbSource.Rows[i + _tempk]["棚番号"].ToString(), blackFont), 500f, 287f, 0);
                                //Insert 出庫番号
                                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase(_dtbSource.Rows[i + _tempk]["組込番号"].ToString(), blackFont), 430f, 225f, 0);
                            }
                            #endregion

                            _tempk++;
                        }
                    }
                    bytes = stream.ToArray();
                }
                File.WriteAllBytes(_PathFile, bytes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemplo n.º 5
0
        private string AddPageNumber(string outputDirectoryPath, string auxFilePath, string name)
        {
            string returnPath = Path.Combine(outputDirectoryPath, $"{name}.pdf");

            byte[] bytes     = File.ReadAllBytes(auxFilePath);
            Font   blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);

            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader reader = new PdfReader(bytes);
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
                    }
                }
                bytes = stream.ToArray();
            }


            File.WriteAllBytes(returnPath, bytes);
            bytes = null;

            if (File.Exists(auxFilePath))
            {
                File.Delete(auxFilePath);
            }

            return(returnPath);
        }
Exemplo n.º 6
0
        public bool WatermarkPDF_SW(string SourcePdfPath, string OutputPdfPath, string WatermarkImageUrl, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
        {
            try
            {
                PdfReader      reader = new PdfReader(SourcePdfPath);
                PdfStamper     stamp  = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
                int            n      = reader.NumberOfPages;
                int            i      = 0;
                PdfContentByte under;
                WatermarkWidth = WatermarkWidth / n;
                //这个地方要注意,是根据页数来动态加载图片地址,有几页就加载几页的图片
                string WatermarkPath  = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/合同备案公章" + n + "/");
                string WatermarkPath2 = "";
                while (i < n)
                {
                    i++;
                    WatermarkPath2 = WatermarkPath + i + ".gif";
                    iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath2);
                    im.SetAbsolutePosition(positionX, positionY);
                    im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);

                    under = stamp.GetUnderContent(i);
                    under.AddImage(im, true);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }
            msg = "加水印成功!";
            return(true);
        }
Exemplo n.º 7
0
    private void addWatermarkInsidePDF(string fileName)
    {
        string sourceFilePath = Server.MapPath("~\\SharingDoc\\") + fileName;

        byte[] bytes = File.ReadAllBytes(sourceFilePath);
        var    img   = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/watermark_img.png"));

        img.ScaleToFit(375, 700);
        img.Alignment = iTextSharp.text.Image.UNDERLYING;
        img.SetAbsolutePosition(100, 200);
        PdfContentByte waterMark;

        using (MemoryStream stream = new MemoryStream())
        {
            PdfReader reader = new PdfReader(bytes);
            using (PdfStamper stamper = new PdfStamper(reader, stream))
            {
                int pages = reader.NumberOfPages;
                for (int i = 1; i <= pages; i++)
                {
                    waterMark = stamper.GetUnderContent(i);
                    waterMark.AddImage(img);
                }
            }
            bytes = stream.ToArray();
        }
        File.WriteAllBytes(sourceFilePath, bytes);
    }
Exemplo n.º 8
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)); // create?
            int        n       = reader.NumberOfPages;
            Rectangle  pagesize;

            for (int i = 1; i <= n; i++)
            {
                PdfContentByte under = stamper.GetUnderContent(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;
                under.SaveState();
                under.SetGState(gs);
                under.SetRGBColorFill(200, 200, 0);
                ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
                                           new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
                                           x, y, 45);
                under.RestoreState();
            }
            stamper.Close();
            reader.Close();
        }
Exemplo n.º 9
0
        private void buttonStampa_Click(object sender, EventArgs e)
        {
            FindAndKillProcess("Acrobat");
            FindAndKillProcess("AcroRd32");

            PdfReader pdfReader = new PdfReader(@"vuota.pdf");
            Rectangle size      = pdfReader.GetPageSize(1);

            using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(@"barcode.pdf", FileMode.Create)))
            {
                foreach (var p in pagine.Select((obj, i) => new { Index = i, Lista = obj }))
                {
                    var indice = p.Index;
                    var pagina = p.Lista;

                    if (indice > 0)
                    {
                        pdfStamper.InsertPage(indice + 1, size);
                    }

                    PdfContentByte cb = pdfStamper.GetUnderContent(indice + 1);
                    foreach (var cf in pagina)
                    {
                        cb.AddImage(creaCodiceBarre(cb, cf, pagina.IndexOf(cf)));
                    }
                }
                pdfStamper.Close();
            }

            Process.Start(@"barcode.pdf");
        }
Exemplo n.º 10
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.º 11
0
        public static void StampPdfWithTemplate(string fileName)
        {
            var          backgroundPath = fileName;
            const string original       = @"Avery5167Template.pdf";
            var          directoryName  = Path.GetDirectoryName(fileName);

            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            var extension      = Path.GetExtension(fileName);
            var resultFileName = $"{fileNameWithoutExtension}WithTemplate{extension}";
            var result         = Path.Combine(
                directoryName ?? throw new InvalidOperationException(),
                resultFileName);

            var originalReader   = new PdfReader(original);
            var backgroundReader = new PdfReader(backgroundPath);
            var stamper          = new PdfStamper(originalReader, new FileStream(result, FileMode.Create));
            var page             = stamper.GetImportedPage(backgroundReader, 1);
            var numberOfPages    = originalReader.NumberOfPages;

            for (var currentPage = 1; currentPage <= numberOfPages; currentPage++)
            {
                var background = stamper.GetUnderContent(currentPage);
                background.AddTemplate(page, 0, 0);
            }
            stamper.Close();
        }
Exemplo n.º 12
0
        //Got this code from http://footheory.com/blogs/donnfelker/archive/2008/05/11/using-itextsharp-to-watermark-write-text-to-existing-pdf-s.aspx
        MemoryStream AddWatermarkText(string watermark, MemoryStream ms)
        {
            PdfReader    reader       = new PdfReader(ms);
            MemoryStream memoryStream = new MemoryStream();

            PdfStamper pdfStamper = new PdfStamper(reader, memoryStream);

            for (int i = 1; i <= reader.NumberOfPages; i++) // Must start at 1 because 0 is not an actual page.
            {
                Rectangle      pageSize        = reader.GetPageSizeWithRotation(i);
                PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(i);
                pdfPageContents.BeginText();                  // Start working with text.
                BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
                pdfPageContents.SetFontAndSize(baseFont, 40); // 40 point font
                pdfPageContents.SetRGBColorFill(255, 0, 0);   // Sets the color of the font, RED in this instance
                float textAngle = (float)GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);

                pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermark, pageSize.Width / 2, pageSize.Height / 2, textAngle);
                pdfPageContents.EndText();    // Done working with text
            }
            pdfStamper.FormFlattening = true; // enable this if you want the PDF flattened.
            pdfStamper.Close();               // Always close the stamper or you'll have a 0 byte stream.

            return(memoryStream);
        }
Exemplo n.º 13
0
        public static void SetPageBackgroundColor(this PdfInfo pdfInfo, int pageNumber, BaseColor color = null)
        {
            if (color == null)
            {
                color = BaseColor.WHITE;
            }

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

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

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

                    pdfInfo.UpdateBytes(ms.ToArray());
                }
            }
        }
Exemplo n.º 14
0
 public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
 {
     try
     {
         PdfReader             reader = new PdfReader(SourcePdfPath);
         PdfStamper            stamp  = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
         int                   n      = reader.NumberOfPages;
         int                   i      = 0;
         PdfContentByte        under;
         iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
         im.SetAbsolutePosition(positionX, positionY);
         im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
         while (i < n)
         {
             i++;
             under = stamp.GetUnderContent(i);
             under.AddImage(im, true);
         }
         stamp.Close();
         reader.Close();
     }
     catch (Exception ex)
     {
         msg = ex.Message;
         return(false);
     }
     msg = "加水印成功!";
     return(true);
 }
Exemplo n.º 15
0
 public static void manipulatePdf(String src, String dest, string Text = DefaultWatermark)
 {
     using (var ms = new MemoryStream(10 * 1024))
     {
         using (var reader = new PdfReader(src))
             using (var stamper = new PdfStamper(reader, ms))
             {
                 PdfContentByte under  = stamper.GetUnderContent(1);
                 Font           f      = new Font(FontFamily.HELVETICA, 45);
                 Phrase         p      = new Phrase(Text, f);
                 var            gstate = new PdfGState {
                     FillOpacity = 0.35f, StrokeOpacity = 0.3f
                 };
                 under.SaveState();
                 under.SetGState(gstate);
                 under.SetColorFill(BaseColor.GRAY);
                 Rectangle realPageSize = reader.GetPageSizeWithRotation(1);
                 var       x            = (realPageSize.Right + realPageSize.Left) / 2;
                 var       y            = (realPageSize.Bottom + realPageSize.Top) / 2;
                 ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER, p, x, y, 45);
                 under.RestoreState();
                 stamper.Close();
                 reader.Close();
             }
         File.WriteAllBytes(dest, ms.ToArray());
     }
 }
Exemplo n.º 16
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.º 17
0
 public static void PdfStampWithNewFile(string watermarkImagePath, string sourceFilePath)
 {
     try
     {
         System.IO.File.Delete(sourceFilePath + "w");
         System.IO.File.Copy(sourceFilePath, sourceFilePath + "w");
         System.IO.File.Delete(sourceFilePath);
         var pdfReader  = new PdfReader(sourceFilePath + "w");
         var pdfStamper = new PdfStamper(pdfReader, new FileStream(sourceFilePath, FileMode.Create));
         var image      = iTextSharp.text.Image.GetInstance(watermarkImagePath);
         ////image.SetAbsolutePosition(15, 200);
         image.SetAbsolutePosition(15, 400);
         for (var i = 0; i < pdfReader.NumberOfPages; i++)
         {
             var content = pdfStamper.GetUnderContent(i + 1);
             content.AddImage(image);
         }
         pdfStamper.Close();
         pdfReader.Close();
         System.IO.File.Delete(sourceFilePath + "w");
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error while Watermarking pdf");
     }
 }
Exemplo n.º 18
0
        public void PdfStampInExistingFileV2(string waterText, string sourceFilePath)
        {
            byte[] bytes = File.ReadAllBytes(sourceFilePath);
            Image  mage  = GetTextWatermark(waterText);
            var    img   = iTextSharp.text.Image.GetInstance(mage, ImageFormat.Png);

            img.GrayFill = 40;
            PdfReader reader = new PdfReader(bytes);

            iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);
            float waterLeft = pagesize.Width - img.Width - 10;
            float waterTop  = pagesize.Height - img.Height - 10;

            img.SetAbsolutePosition(waterLeft, waterTop);
            PdfContentByte waterMark;

            using (MemoryStream stream = new MemoryStream())
            {
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        waterMark = stamper.GetUnderContent(i);
                        waterMark.AddImage(img);
                    }
                }
                bytes = stream.ToArray();
            }
            File.WriteAllBytes(sourceFilePath, bytes);
        }
Exemplo n.º 19
0
        public static byte[] AddPageNumbers(byte[] filePdf, Font font, string format, bool differentByPage)
        {
            using (var stream = new MemoryStream())
            {
                var reader = new PdfReader(filePdf);

                using (var stamper = new PdfStamper(reader, stream))
                {
                    var pages = reader.NumberOfPages;
                    for (var i = 1; i <= pages; i++)
                    {
                        if (i == 1 || i == pages)
                        {
                            continue;
                        }

                        var align = Element.ALIGN_RIGHT;

                        var x = 568f;
                        if (differentByPage && i % 2 != 0)
                        {
                            x = 52f;
                        }
                        var phrase = new Phrase(string.Format(format, i - 1), font);
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), align, phrase, x, 15f, 0);
                    }
                }
                return(stream.ToArray());
            }
        }
Exemplo n.º 20
0
        //*** une los archivos, está actualmente aplicado
        public static void MergePDF(string src, string src1, string final)
        {
            //altotal 856
            float y = -302;

            final = Properties.Settings.Default.PathDefecto + @"generadasfacturas\" + final;

            PdfReader  reader  = new PdfReader(src);
            PdfStamper stamper =
                new PdfStamper(reader, new FileStream(final, FileMode.Create));

            PdfContentByte canvas = stamper.GetUnderContent(1);

            PdfReader       r;
            PdfImportedPage page;

            PdfReader s_reader = new PdfReader(src1);
            Rectangle pageSize = reader.GetPageSize(1);

            int n = reader.NumberOfPages;

            for (int i = 1; i <= n; i++)
            {
                r    = new PdfReader(src1);
                page = stamper.GetImportedPage(r, 1);
                canvas.AddTemplate(page, 0, y);
                stamper.Writer.FreeReader(r);
                r.Close();
            }

            stamper.Close();
        }
Exemplo n.º 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            //get upload file path directory and set up new file location
            pathin = openFileDialog1.FileName;


            pathout = Path.GetDirectoryName(pathin) + "/SOP Short Picking Ticket Form Note.pdf";

            try
            {
                //create a document object
                var doc = new Document(PageSize.A4);

                //create PdfReader object to read from the existing document
                PdfReader reader = new PdfReader(pathin);
                pageNumber = reader.NumberOfPages;
                range      = "1-" + pageNumber.ToString();
                if (String.IsNullOrEmpty(endTextBox.Text))
                {
                    startPage   = 1;
                    endnotePage = pageNumber;
                }
                else
                {
                    startPage   = Convert.ToInt32(startTextBox.Text);
                    endnotePage = Convert.ToInt32(endTextBox.Text);
                }
                //select  pages from the original document
                reader.SelectPages(range);

                //create PdfStamper object to write to get the pages from reader
                PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
                // PdfContentByte from stamper to add content to the pages over the original content

                for (int i = startPage; i <= endnotePage; i++)
                {
                    PdfContentByte pbover = stamper.GetOverContent(i);
                    //add content to the page using ColumnText
                    ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(textBox1.Text), 100, 400, 0);
                    // PdfContentByte from stamper to add content to the pages under the original content
                    PdfContentByte pbunder = stamper.GetUnderContent(pageNumber);
                }



                //close the stamper
                stamper.Close();
                //close the reader
                reader.Close();
                //clean up
                doc.Close();
            }
            catch (FormatException)
            {
                MessageBox.Show("please enter an interger");
            }
            MessageBox.Show("note added to the pdf");
            Process.Start(pathout);
        }
Exemplo n.º 22
0
        public static void PDFGenerator_A3Landscape(string filename, string HTML_DATA)
        {
            string filepath = HttpContext.Current.Server.MapPath("~/PDF/");

            StringWriter   sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            Panel p = new Panel();

            p.Controls.Add(new LiteralControl(HTML_DATA));
            p.RenderControl(hw);

            StringReader sr     = new StringReader(sw.ToString());
            Document     pdfDoc = new Document(PageSize.A3.Rotate(), 10f, 10f, 10f, 0f);

            pdfDoc.SetMargins(50, 50, 80, 50);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            //PdfWriter.GetInstance(pdfDoc, new FileStream(filepath + filename, FileMode.Create));

            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filepath + filename, FileMode.Create));

            pdfDoc.Open();

            //using header class started
            writer.PageEvent = new Header_Landscape();
            Paragraph welcomeParagraph = new Paragraph();

            pdfDoc.Add(welcomeParagraph);
            //using header class ended



            //starting xmlworker
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            //htmlparser.StartDocument();
            //htmlparser.Parse(sr);

            //htmlparser.EndDocument();
            //htmlparser.Close();
            pdfDoc.Close();
            //adding page number
            byte[] bytes     = File.ReadAllBytes(filepath + filename);
            Font   blackFont = FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.BLACK);

            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader reader = new PdfReader(bytes);
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                    for (int i = 1; i <= pages; i++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase("Page " + i.ToString() + " of " + pages.ToString(), blackFont), 568f, 15f, 0);
                    }
                }
                bytes = stream.ToArray();
            }
            File.WriteAllBytes(filepath + filename, bytes);
        }
Exemplo n.º 23
0
        public bool WatermarkPDF(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg, int ryCount)
        {
            try
            {
                PdfReader      reader = new PdfReader(SourcePdfPath);
                PdfStamper     stamp  = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
                int            n      = reader.NumberOfPages;
                int            i      = 0;
                PdfContentByte under;

                while (i < n)
                {
                    i++;
                    under = stamp.GetUnderContent(i);
                    iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
                    im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
                    //im.SetAbsolutePosition(positionX, positionY);

                    float height = 841;
                    if (i == n)
                    {
                        string imgHYPath           = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/核验章.png");
                        iTextSharp.text.Image imHY = iTextSharp.text.Image.GetInstance(imgHYPath);
                        imHY.ScaleAbsolute(100, 50);
                        if (i == 1)//说明就一页
                        {
                            height = height - 160 - ryCount * 23 - 115;
                            //再加上已核验的章
                            imHY.SetAbsolutePosition(200, height + 35);
                        }
                        else
                        {
                            height = height - (ryCount - 18) * 23;
                            //再加上已核验的章
                            imHY.SetAbsolutePosition(200, height + 35);
                        }
                        under.AddImage(imHY, true);
                        im.SetAbsolutePosition(positionX, height);
                    }
                    else//不是第一页,也不是最后一页
                    {
                        im.SetAbsolutePosition(positionX, positionY);
                    }

                    under.AddImage(im, true);
                }
                stamp.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                msg = ex.Message;

                return(false);
            }

            msg = "加水印成功!";
            return(true);
        }
Exemplo n.º 24
0
        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        public static void AddWatermark(string inputFilePath, string text, out string outFilePath)
        {
            Console.WriteLine(inputFilePath);
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;
            string     tempPath   = Path.GetDirectoryName(inputFilePath) + "\\" + Path.GetFileNameWithoutExtension(inputFilePath) + "_temp.pdf";

            outFilePath = Path.GetDirectoryName(inputFilePath) + "\\" + Path.GetFileNameWithoutExtension(inputFilePath) + "_watermark.pdf";
            File.Copy(inputFilePath, tempPath);
            try
            {
                pdfReader  = new PdfReader(tempPath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outFilePath, FileMode.Create));
                int       total = pdfReader.NumberOfPages + 1;
                Rectangle psize = pdfReader.GetPageSize(1);
                //float width = psize.Width;
                //float height = psize.Height;
                PdfContentByte content;
                BaseFont       font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState      gs   = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    //content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    content        = pdfStamper.GetUnderContent(i); //在内容下方加水印
                    gs.FillOpacity = 0.3f;                          //透明度
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.Gray);
                    content.SetFontAndSize(font, 30);
                    content.SetTextMatrix(0, 0);

                    //重复添加水印
                    for (int j = 0; j < 5; j++)
                    {
                        content.ShowTextAligned(Element.ALIGN_CENTER, text, (50.5f + i * 250), (40.0f + j * 150), (total % 2 == 1 ? -45 : 45));
                    }
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                File.Delete(tempPath);
            }
        }
Exemplo n.º 25
0
        //----------------------------------------------------------------------------------------------------

        private void SignPdf(MemoryStream stream, ReportModel model, string fileName)
        {
            var        reader    = new PdfReader(stream.ToArray());
            PdfStamper stamper   = new PdfStamper(reader, stream);
            var        signature = $"eZign: {model.HashIdEmployee}        Reference: {fileName}";

            int numberOfPages = reader.NumberOfPages;

            for (int i = 2; i <= numberOfPages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase($"{i} / {numberOfPages}", _pdfHelper.Font), 297f, 15f, 0);
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_LEFT, new Phrase(signature, _pdfHelper.SignFont), 18f, 825f, 0);
            }

            stamper.Close();
            reader.Close();
        }
Exemplo n.º 26
0
        static void PrintPageNumber(PdfStamper stamper, PageNumber pagingOptions, int currrent, int total)
        {
            float left = 0f, bottom = 0f;

            var font       = pagingOptions.FontOption.Font;
            var text       = pagingOptions.GetText(currrent, total);
            var textPhrase = new Phrase(text, font);
            var textWidth  = font.GetCalculatedBaseFont(true).GetWidthPoint(text, font.Size);
            var pageBox    = stamper.Reader.GetPageSize(currrent);

            if (pagingOptions.Alignment == Alignment.Center && (pagingOptions.PrintLocation == PageSection.Bottom || pagingOptions.PrintLocation == PageSection.Top))
            {
                left = (pageBox.Height + textWidth) / 2;
            }
            if (pagingOptions.Alignment == Alignment.Right && (pagingOptions.PrintLocation == PageSection.Bottom || pagingOptions.PrintLocation == PageSection.Top))
            {
                left = pageBox.Height - textWidth - 15;
            }
            if (pagingOptions.Alignment == Alignment.Left && (pagingOptions.PrintLocation == PageSection.Bottom || pagingOptions.PrintLocation == PageSection.Top))
            {
                left = pageBox.Width - 15;
            }

            if (pagingOptions.Alignment == Alignment.Center && (pagingOptions.PrintLocation == PageSection.Right || pagingOptions.PrintLocation == PageSection.Left))
            {
                bottom = (pageBox.Width + textWidth) / 2;
            }
            if (pagingOptions.Alignment == Alignment.Right && (pagingOptions.PrintLocation == PageSection.Right || pagingOptions.PrintLocation == PageSection.Left))
            {
                bottom = textWidth + 15f;
            }
            if (pagingOptions.Alignment == Alignment.Left && (pagingOptions.PrintLocation == PageSection.Right || pagingOptions.PrintLocation == PageSection.Left))
            {
                bottom = pageBox.Width - textWidth - 15;
            }

            if (pagingOptions.PrintLocation == PageSection.Bottom)
            {
                bottom = 15f;
            }
            if (pagingOptions.PrintLocation == PageSection.Top)
            {
                bottom = pageBox.Width - 15;
            }
            if (pagingOptions.PrintLocation == PageSection.Left)
            {
                left = 15f;
            }
            if (pagingOptions.PrintLocation == PageSection.Right)
            {
                left = pageBox.Height - 15;
            }

            ColumnText.ShowTextAligned(stamper.GetUnderContent(currrent), Element.ALIGN_CENTER, textPhrase, bottom, left, 0,
                                       pagingOptions.Direction == Direction.RightToLeft
                    ? PdfWriter.RUN_DIRECTION_RTL
                    : PdfWriter.RUN_DIRECTION_DEFAULT, 1);
        }
Exemplo n.º 27
0
        public static void FoliarPdf(string RutaPDf)
        {
            //System.Drawing.Color? color = System.Drawing.Color.Black;
            //FolioPosition folioPosition = FolioPosition.BottomRight;
            //FolioType folioType = FolioType.Numeric;
            string fechaProceso = $"Fecha Proceso: {DateTime.Now.ToString("dd/MM/yyyy")}";
            string folioPrefix  = "Pag. ";
            string folioSuffix  = "";
            //string folioFont = FontFactory.TIMES_ROMAN.ToString();
            //FolioFace folioFace = FolioFace.Roman;
            float     folioSize = 9;
            PdfReader reader    = new PdfReader(RutaPDf);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int        totalNumberOfPages = reader.NumberOfPages;
                string     folioTotalNumber   = totalNumberOfPages.ToString();
                PdfStamper pdfStamper         = new PdfStamper(reader, memoryStream);
                for (int i = 1; i <= totalNumberOfPages; i++)
                {
                    // skip adding folio if not started yet
                    if (i < 1)
                    {
                        continue;
                    }
                    // page number preparation
                    string folioNumber = i.ToString();
                    string folio       = folioPrefix + folioNumber;
                    folio += " de " + folioTotalNumber;
                    folio += folioSuffix;
                    BaseFont       baseFont        = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(i);
                    // apply style
                    pdfPageContents.BeginText();
                    pdfPageContents.SetFontAndSize(baseFont, folioSize);
                    //pdfPageContents.SetRGBColorFill(Convert.ToInt32(color.Value.R),
                    //    Convert.ToInt32(color.Value.G), Convert.ToInt32(color.Value.B));


                    // prepare x,y cords 0,0 = bottom left
                    Rectangle pageSize = reader.GetPageSizeWithRotation(i);
                    float     strWidth = pdfPageContents.GetEffectiveStringWidth(folio, false);
                    const int padding  = 10;
                    float     foliox   = padding;
                    float     folioy   = folioSize;
                    foliox = pageSize.Width - strWidth - padding;
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, folio, foliox, folioy, 0);

                    strWidth = pdfPageContents.GetEffectiveStringWidth(fechaProceso, false);
                    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, fechaProceso, padding + strWidth, folioy, 0);

                    pdfPageContents.EndText();
                }
                pdfStamper.Close();
                reader.Close();
                File.WriteAllBytes(RutaPDf, memoryStream.ToArray());
            }
        }
Exemplo n.º 28
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src
         * @param src the original PDF
         * @param stationery the resulting PDF
         */
        public byte[] ManipulatePdf(byte[] src, byte[] stationery)
        {
            ColumnText ct  = new ColumnText(null);
            string     SQL =
                @"SELECT country, id FROM film_country 
ORDER BY country
";

            using (var c = AdoDB.Provider.CreateConnection())
            {
                c.ConnectionString = AdoDB.CS;
                using (DbCommand cmd = c.CreateCommand())
                {
                    cmd.CommandText = SQL;
                    c.Open();
                    using (var r = cmd.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            ct.AddElement(new Paragraph(
                                              24, new Chunk(r["country"].ToString())
                                              ));
                        }
                    }
                }
            }
            // Create a reader for the original document and for the stationery
            PdfReader reader      = new PdfReader(src);
            PdfReader rStationery = new PdfReader(stationery);

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create an imported page for the stationery
                    PdfImportedPage page = stamper.GetImportedPage(rStationery, 1);
                    int             i    = 0;
                    // Add the content of the ColumnText object
                    while (true)
                    {
                        // Add a new page
                        stamper.InsertPage(++i, reader.GetPageSize(1));
                        // Add the stationary to the new page
                        stamper.GetUnderContent(i).AddTemplate(page, 0, 0);
                        // Add as much content of the column as possible
                        ct.Canvas = stamper.GetOverContent(i);
                        ct.SetSimpleColumn(36, 36, 559, 770);
                        if (!ColumnText.HasMoreText(ct.Go()))
                        {
                            break;
                        }
                    }
                }
                return(ms.ToArray());
            }
        }
Exemplo n.º 29
0
        /**
         * This method edits the immediate contents of a page, i.e. its content stream.
         * It explicitly does not descent into form xobjects, patterns, or annotations.
         */
        public void EditPage(PdfStamper pdfStamper, int pageNum)
        {
            var pdfReader        = pdfStamper.Reader;
            var page             = pdfReader.GetPageN(pageNum);
            var pageContentInput = ContentByteUtils.GetContentBytesForPage(pdfReader, pageNum);

            page.Remove(PdfName.CONTENTS);
            EditContent(pageContentInput, page.GetAsDict(PdfName.RESOURCES), pdfStamper.GetUnderContent(pageNum));
        }
Exemplo n.º 30
0
        /// <summary>
        /// 插入文字浮水印
        /// </summary>
        /// <param name="getPDFContent">PDF內容</param>
        /// <param name="textWaterMark">文字浮水印內容</param>
        /// <returns></returns>
        public byte[] InsertWaterMark(
            byte[] getPDFContent,
            string textWaterMark
            )
        {
            MemoryStream msInput = new MemoryStream();

            byte[] result = new byte[] { };

            using (PdfReader pdfReader = new PdfReader(getPDFContent))
            {
                using (PdfStamper pdfStamper = new PdfStamper(pdfReader, msInput))
                {
                    int            pageTotal = pdfReader.NumberOfPages + 1;
                    PdfContentByte content;
                    PdfGState      gs        = new PdfGState();
                    var            unicodefy = new UnicodeFontFactory();

                    // 第一頁索引起始是1
                    for (int i = 1; i < pageTotal; i++)
                    {
                        // 取得當前頁面Size
                        Rectangle psize = pdfReader.GetPageSize(1);

                        // 取得Page 寬與高
                        float width  = psize.Width;
                        float height = psize.Height;

                        content = pdfStamper.GetUnderContent(i); //在内容上方加水印

                        // 設置透明度
                        gs.FillOpacity = 0.3f;
                        content.SetGState(gs);

                        //寫入內容
                        content.BeginText();
                        content.SetColorFill(BaseColor.BLACK);
                        content.SetFontAndSize(unicodefy.KAIUFont, 30);
                        content.SetTextMatrix(0, 0);
                        content.ShowTextAligned(
                            Element.ALIGN_CENTER, // 對齊
                            textWaterMark,        // 內容
                            width / 2,            // X軸
                            height - 200,         // Y軸
                            5.56f                 // 旋轉幅度
                            );
                        content.EndText();
                    }
                }

                msInput.Close();
                result = msInput.ToArray();
            }

            return(result);
        }