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();
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();