How do I add an Image Mask?

21 views
Skip to first unread message

Ryan

unread,
Jan 10, 2017, 7:13:46 PM1/10/17
to PDFTron PDFNet SDK
Question:

I am trying to add an image mask using the following code, but get an exception.

using (PDFDoc doc = new PDFDoc())
using (ElementBuilder bld = new ElementBuilder())
using (ElementWriter writer = new ElementWriter())
{
   
Page page = doc.PageCreate();
    writer
.Begin(page);
   
Image img = Image.Create(doc, "Image.png");
   
Image maskImage = Image.Create(doc, "MaskImage.tif");
    img
.SetMask(maskImage); // throws the exception!!!
   
System.Drawing.Bitmap bmp;
   
Element element = bld.CreateImage(img, new Matrix2D(200, 0, 0, 250, 50, 500));
    writer
.WritePlacedElement(element);
    writer
.End();
    doc
.PagePushBack(page);
    doc
.Save("out.pdf", SDFDoc.SaveOptions.e_remove_unused);
}

The exception:
 
Unhandled Exception: pdftron.Common.PDFNetException: Exception:
         
Message: Bad params
         
Conditional expression: !IsImageMask() && image_mask.IsImageMask()
         
Filename   : Image.cpp
         
Function   : trn::PDF::Image::SetMask
         
Linenumber : 864

Answer:

Image.Create creates a "regular" image, which needs two changes to be a Mask.

Image maskImage = Image.Create(doc, "MaskImage109.tif");
Obj obj = maskImage.GetSDFObj();
obj
.PutBool("ImageMask", true);
obj
.Erase("ColorSpace");


So final code would be

using (PDFDoc doc = new PDFDoc())
using (ElementBuilder bld = new ElementBuilder())
using (ElementWriter writer = new ElementWriter())
{
   
Page page = doc.PageCreate();
    writer
.Begin(page);
   
Image img = Image.Create(doc, "Image.png");
   
Image maskImage = Image.Create(doc, "MaskImage.tif");
   
Obj obj = maskImage.GetSDFObj();
    obj
.PutBool("ImageMask", true);
    obj
.Erase("ColorSpace");
    img
.SetMask(maskImage);
   
System.Drawing.Bitmap bmp;
   
Element element = bld.CreateImage(img, new Matrix2D(200, 0, 0, 250, 50, 500));
    writer
.WritePlacedElement(element);
    writer
.End();
    doc
.PagePushBack(page);
    doc
.Save("out.pdf", SDFDoc.SaveOptions.e_remove_unused);
}



Reply all
Reply to author
Forward
0 new messages