Friday, March 29, 2013

Replace/Mask Images of PDF file using Itextsharp

Article is about masking or replacing the images from PDF documents using iTextSharp. 

iTextSharp  is a free .NET component, you can download the DLL from http://sourceforge.net/projects/itextsharp/

After downloading the DLL, add reference of DLL in project by clicking on Add Reference from solution explorer.


Namespace :

using iTextSharp.text;
using iTextSharp.text.pdf;



Code:

   PdfReader pdf = new PdfReader("Test.pdf");
            PdfStamper stp = new PdfStamper(pdf, new FileStream("output.pdf",
FileMode.Create));
            


PdfWriter writer = stp.Writer;
             for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
            {
               
                Image img = Image.GetInstance("Img.jpg");
            PdfDictionary pg = pdf.GetPageN(pageNumber);
            PdfDictionary res =
              (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
            PdfDictionary xobj =
              (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
            if (xobj != null)
            {
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        PdfName type =
                          (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                        if (PdfName.IMAGE.Equals(type))
                        {
                            PdfReader.KillIndirect(obj);
                            Image maskImage = img.ImageMask;
                            if (maskImage != null)
                                writer.AddDirectImageSimple(maskImage);
                            writer.AddDirectImageSimple(img, (PRIndirectReference)obj);
                            break;
                        }
                    }
                }
            }
        }
            stp.Close();

3 comments:

  1. thanks a lot for piece of code with checking ImageMask on null.
    It's definetly smart solution.

    ReplyDelete
  2. thnx for sharing such a valuable information….I am using zetpdf to generate pdf in asp.net…I would also suggest you to use zetpdf…It makes the job easy..

    ReplyDelete
  3. This code does implement Replace/Mask Images of PDF file, but after all, it is open source code, it is okay to do personal products. If you want to use it for commercial purposes, it is recommended to look at this .net pdf library, which is more stable and reliable.

    ReplyDelete