Insert a Picture into the Picture/Image Content Control using Open XML SDK 2.0

I have created a word template as follows
Here PizzaPicture is a Picture Content Control, PizzaName is a Plain Text Content Control and PizzaDescription is a Rich Text Content Control
I am able to assign text to PizzaName and PizzaDescription Easily but not able to even locate the PizzaPicture. Here is my code
using (WordprocessingDocument document = WordprocessingDocument.Open(@".\test.docx", true)) {
MainDocumentPart mainPart = document.MainDocumentPart;
DocumentFormat.OpenXml.Wordprocessing.Text text = null;
SdtContentBlock pizzaNameBlock = null;
SdtContentBlock pizzaDescriptionBlock = null;
//SdtContentBlock pizzaPictureBlock = null;
List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().ToList();
foreach (SdtBlock sdt in sdtList)
Console.WriteLine(sdt.SdtProperties.GetFirstChild<Tag>().Val.Value);
SdtBlock s1 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaName").Single();
SdtBlock s2 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaDescription").Single();
SdtBlock s3 = mainPart.Document.Body.Descendants<SdtBlock>().FirstOrDefault(r =>
SdtProperties p = r.Elements<SdtProperties>().FirstOrDefault();
if (p != null)
Console.WriteLine("P is not null");
// Is it a picture content control?
SdtContentPicture pict =
p.Elements<SdtContentPicture>().FirstOrDefault();
if (pict != null) Console.WriteLine("Pict is not null");
// Get the alias.
SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();
if (pict != null && a.Val == "PizzaPicture")
return true;
return false;
if (s3 == null) {
Console.Write(" s3 is Null");
} else {
Console.WriteLine("s3 not null");
if (s1 != null) {
pizzaNameBlock = s1.Descendants<SdtContentBlock>().FirstOrDefault();
text = pizzaNameBlock.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();
// here you can set the current time
text.Text = "Peperoni";
Console.WriteLine(text.Text);
string embed = null;
if (s3 != null)
Drawing dr = s3.Descendants<Drawing>().FirstOrDefault();
if (dr != null)
Blip blip = dr.Descendants<Blip>().FirstOrDefault();
if (blip != null)
embed = blip.Embed;
if (embed != null)
IdPartPair idpp = document.MainDocumentPart.Parts
.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
if (idpp != null)
ImagePart ip = (ImagePart)idpp.OpenXmlPart;
using (FileStream fileStream =
File.Open(@"c:\temp\pepperoni.jpg", FileMode.Open))
ip.FeedData(fileStream);
if (s2 != null) {
pizzaDescriptionBlock = s2.Descendants<SdtContentBlock>().FirstOrDefault();
string altChunkId = "AltChunkId12345";
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);
chunk.FeedData(File.Open(@".\html.txt", FileMode.Open));
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
////Replace content control with altChunk information
OpenXmlElement parent = pizzaDescriptionBlock.Parent;
parent.InsertAfter(altChunk, pizzaDescriptionBlock);
pizzaDescriptionBlock.Remove();
mainPart.Document.Save();
document.Close();
Here the call mainPart.Document.Descendants<SdtBlock>().ToList(); returns me only 2 items PizzaName, PizzaDescription but
no PizzaPicture.
Secondly the line   SdtContentPicture pict =  p.Elements<SdtContentPicture>().FirstOrDefault();
returns NULL. So it seems that there is no element of type SdtContentPicture.
What am I doing wrong? I am pretty sure that I have put PizzaPicture as a Picture content control.
My objective is to locate this control in the document and then insert an image into it programmatically.
MSDNStudent Knows not much!

Hi,
I'm running some test on your code, and I'll come back as soon as I get some update. But before that, I would recommend you to bind customXMLPart with the content controls via Content Control Tool Kit,
which enables us to bind customXMLPart with CC by dragging and dropping.
After binding, you can change contents of the template via OpenXML SDK easily as the following code:
private void button1_Click(object sender, EventArgs e)
string fileName = @"C:\CCTest.docx";
WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true);
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
CustomXmlPart customPart = mainPart.CustomXmlParts.FirstOrDefault();
//convert image into string
string picName = @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg";
System.IO.FileStream fileStream = System.IO.File.Open(picName, System.IO.FileMode.Open);
System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream);
byte[] byteArea;
byteArea = br.ReadBytes(System.Convert.ToInt32(fileStream.Length));
string picString = System.Convert.ToBase64String(byteArea);
//Load the XML template
string DataString = Properties.Resources.XMLData;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(DataString);
//change the value
XmlNodeList xmlNode = xmlDoc.GetElementsByTagName("pizzaPic");
xmlNode[0].InnerText = picString;
xmlNode = xmlDoc.GetElementsByTagName("pizzaName");
xmlNode[0].InnerText = "Pizza Name";
xmlNode = xmlDoc.GetElementsByTagName("pizzaDescription");
xmlNode[0].InnerText = "Pizza Description";
//write the custom xml data into the customxmlpart
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(customPart.GetStream(System.IO.FileMode.Create), System.Text.Encoding.UTF8);
writer.WriteRaw(xmlDoc.InnerXml);
writer.Flush();
writer.Close();
fileStream.Close();
br.Close();
mainPart.Document.Save();
wordDoc.Close();
and the XML template of the project would something like:
<?xml version="1.0"?>
<Pizza xmlns="http://Test/ContentControls/Pizzas">
<pizzaPic></pizzaPic>
<pizzaName></pizzaName>
<pizzaDescription></pizzaDescription>
</Pizza>
I hope this helps.
Calvin Gao[MSFT]
MSDN Community Support | Feedback to us

Similar Messages

  • Somehow ejbCreate method of an Entity EJB is not inserting a record into the database. I'm using BMP and calling the Entity bean method from a servlet. I'm using NAS 4.0 sp5 on Win 2k.

    Also if I call the insert query from within the servlet it works fine. I have disabled global transactions. Am I missing something out ? Please
    any help would be greatly appreciated.

    May be your servlet is not able to lookup the EJB. You can use some print statements and see whether lookup ok or not.
    Just a guess.
    Plese get back, if any queries.
    Thanks,
    Rakesh.

  • I inserted a HTML5 video in page, when I test it in a Browser, I see the poster image and controls, But when I click play button the video goes white, slider moves like its playing, but just white picture. There was no audio included in video. Please help

    I inserted a HTML5 video in page, when I test it in a Browser, I see the poster image and controls, But when I click play button the video goes white, slider moves like its playing, but just white picture. There was no audio included in video. Please help

    Without a link, it's anybody's guess.
    It could be a problem the video rendering itself.  Which software did you use?
    Did you export to the 3 file types -- MP4, OGG and WEBM to support all browsers?
    Does your web server support those 3 MIME file types?
    Nancy O.

  • How do you insert a picture into another picture?

    How do you insert a picture into another picture.  For example, one person is missing from family photo & I'd like to insert that person's face.

    By using an external editor:
    In order of price here are some suggestions:
    Seashore (free)
    The Gimp (free)
    Graphic Coverter ($45 approx)
    Acorn ($50 approx)
    Pixelmator ($50 approx)
    Photoshop Elements ($75 approx)
    There are many, many other options. Search on MacUpdate. You can set Photoshop (or any image editor) as an external editor in iPhoto. (Preferences -> General -> Edit Photo: Choose from the Drop Down Menu.) This way, when you double click a pic to edit in iPhoto it will open automatically in Photoshop or your Image Editor, and when you save it it's sent back to iPhoto automatically. This is the only way that edits made in another application will be displayed in iPhoto.

  • Is there a possibility to print the filename into the picture?

    Is there a possibility to print the filenames into the picture or into the slideshow? When presenting photos to clients over Apple TV there must be a way to find the image name for ordering.
    Any ideas, I did not find anything!

    Unsure about slide show in Ap, but when printing llok for this dialogue box, it prints any metadata;
    You just need to select the more options bottom left.
    Tony

  • Importing pictures into the item master data

    Hello, everyone,
    I want to import pictures into the items master data - does anyone know which size the picture should have?
    The problem is - i just tested it with some pics of 640x480, but the placeholder in the item data must be smaller, so the picture is scaled down and as result of that it doesn't look good (the colors are falsified and there are also some artifacts). If I double-click the picture and it's opened in an own window in its original resolution - everything is fine..but i want a good quality of the picture in the item data already.
    So my first idea was to make pictures of the resolution of that placeholder in SBO, but i don't know how to get this. Any ideas?
    Best Regards,
    Leon Detzel

    Hi Ulrich
    The picture size does not matter, but rather a setting in Administration > System Initialization > General settings > Display TAB. On this tab you will find a setting with a drop down called "Ext. Image Processing". Set this to full and the full quality of any pictures will be used, but of course resized to fit the field. Bear in mind that images are not embedded in the tables but only the file name of the image is stored in the table.
    Kind regards
    Peter Juby

  • Encode a message into the picture

    Hi,
    regarding the subject above, i know how to encode a static message (which mean predefined the message) into a picture..
    But when it come to the dynamic message (user can enter message), i really no idea on how to encode it in the picture..
    example for how i encode it for static msg :
    predefined msg = "ON"
    O = 79 = 01 00 11 11 c1, c2, c3, c4
    N = 78 = 01 00 11 10 d1, d2, d3, d4
    //0xFC = 1111 1100 <-- used this to remove the last 2 bits
    int c1=1, c2=0, c3=3, c4=3;               //O
    int d1=1, d2=0, d3=3, d4=2;               //N
    int alpha, red, green, blue;
    //unpack the individual pixel n process
    alpha     = (pixels[1]>>24) & 0xFF;
    red     = ((pixels[1]>>16) & 0xFC) + c1;          
    green     = ((pixels[1]>>8) & 0xFC) + c2;
    blue     = (pixels[1] & 0xFC)     + c3;
    //repack the pixels
    pixels[1] = (alpha<<24) | (red<<16) | (green<<8) | blue;
    //unpack the individual pixel n process
    alpha     = (pixels[2]>>24) & 0xFF;
    red     = ((pixels[2]>>16) & 0xFC) + c4;          
    green     = ((pixels[2]>>8) & 0xFC) + d1;
    blue     = (pixels[2] & 0xFC)     + d2;
    //repack the pixels
    pixels[2] = (alpha<<24) | (red<<16) | (green<<8) | blue;
    //unpack the individual pixel n process
    alpha     = (pixels[3]>>24) & 0xFF;
    red     = ((pixels[3]>>16) & 0xFC) + d3;      
    green     = ((pixels[3]>>8) & 0xFC) + d4;
    blue     = (pixels[3] & 0xFC); // no use.... finish used all the bits
    //repack the pixels
    pixels[3] = (alpha<<24) | (red<<16) | (green<<8) | blue;
    But when came to dynamic msg.. i really no idea on how to continue..
    when i get everything ready.. (the msg length, each char value) in the for loop..
    for(int j=0; j<length; j++){
    msg[j] = message.charAt(j);
    value[j] = (int) msg[j];
    //this is to get the binary no.
    c1= (value[j]>>6) & 0x03;
    c2= (value[j]>>4) & 0x03;
    c3= (value[j]>>2) & 0x03;
    c4= value[j] & 0x03;
    Encode(); //call a method to encode the msg into the picture
    wanted to encode it in the picture..
    but the requirement is encode only in the RGB and not alpha..
    so when i get the value (O = 01 00 11 11)
    c1 = 1 c2 =0 c3=3 c4=3
    alpha     = (pixels[1]>>24) & 0xFF;
    red     = ((pixels[1]>>16) & 0xFC) + c1;          
    green     = ((pixels[1]>>8) & 0xFC) + c2;
    blue     = (pixels[1] & 0xFC)     + c3;
    pixels[1] = (alpha<<24) | (red<<16) | (green<<8) | blue;
    but the c4 is not encoded yet... so how ?? what should i do in this method ? because after processing this, it should go back to the for loop to continue the next char.
    c1,c2,c3,c4 will be initialized with the new value again...
    As you can see in the static example, c4 is used in the pixels[2]... then continue with the next char's 1st 4 bit (d1,d2)..
    d3 & d4 is used in the pixels[3]...
    err.. hope you can understand my question and give me some ideas on "encoding a message into the picture"
    thanks and appreciate every single idea & help ;)

    Take a look in the indesign-server-plugin-techniques.pdf in the section on MessageLog for more info.
    Something interesting is that code that calls CAlert methods get converted into MessageLogs.
    Your use of the word "console" makes me think that you are coding for Mac. If that's the case you could create some Mac code and use NSLog to dump to console.
    Create a MyLog.mm file with something like:
    #import <Foundation/Foundation.h>
    void MyLogMessage(char *msg)
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"%s", msg);
    [pool release];
    Remember to add the Foundation framework to your project, and change the compile option from compile all files as C++ to compile according type.

  • Limitations of trial version 13? I cannot load pictures into the photomerge panorama window either from' browse' or 'add open files'.

    On Adobe's web site it states the trial version has all functionality.  FAQ, common questions & answers | Adobe Photoshop Elements 13 "These trial versions are fully functional, so every feature and aspect of the product is available for you to test-drive. Product trials can easily be converted for unrestricted use without the necessity to reinstall the software in most cases."
    However, I cannot load pictures into the photomerge panorama window either from' browse' or 'add open files'. When I select either way nothing happens.This happens if I enter panorama from photo editor and/or organizer.
    Can anybody enlighten me about this?
    Thanks,
    Barry

    It seems your Samba is denying access to these files & dirs. My best guess would be that either the Samba user is not allowed to write (and read) those (in which case you'd have to modify the permissions accordingly) or Samba sets, when the share is mounted, the permissions such that your user is not allowed to read and write (you may in this case try to just set permissions for you to allow you what you want to do; or use "create mask" or "directory mask" or "writable" in your samba config. ).
    Also, what do the logs say about this? According to your samba conf they are in /var/log/samba/%m.log where %m is the hostname or IP.

  • I can't get my pictures into the public folder on the iPad 3.  Can anyone walk me through the steps?

    I can't get my pictures into the public folder on the iPad 3.  Can someone walk me through the steps?

    Ok, I'll give it a try.
    Presuming you already have a Dropbox account, and you have the app on your pad.
    Open the app, navigate to public folder.  Touch the upload icon at the bottom.  It will show you everything you have already uploaded.  To upload a new picture, then touch the plus sign at the top right.     You can create one or more subfolders to organize it however you want.
    Hit the plus sign again if needed, and the photo listing will show up.  Find the photos you want and mark them by touching them.  Then touch the blue word upload in the upper right.
    ( the directions assume the pad is in the landscape mode.)
    That's really all there is to it.  As I typed this I opened and uploaded a couple of pics to get the steps right.

  • SCCM 2012: Failed to insert OSD binaries into the WIM file' error when you create a MDT Task Sequence

    Hi,
    When I try to import the MDT boot image X86, I get the following error:
    Started processing.
    Creating boot image.
    Copying WIM file.
    Mounting WIM file.
    WIM file mounted.
    Setting Windows PE system root.
    Set Windows PE system root.
    Set Windows PE scratch space.
    Adding standard components.
    Adding component: winpe-mdac
    Adding extra content from: C:\Users\ADMINI~1.afO\AppData\Local\Temp\3\sfup2yp2.0rt
    Unmounting WIM.
    Copying WIM to the package source directory.
    Creating boot image package.
    Error while importing Microsoft Deployment Toolkit Task Sequence.
    Failed to insert OSD binaries into the WIM file
    Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryException: The SMS Provider reported an error. ---> System.Management.ManagementException: Generic failure
       at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
       at System.Management.ManagementObject.Put(PutOptions options)
       at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlResultObject.Put(ReportProgress progressReport)
       --- End of inner exception stack trace ---
       at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlResultObject.Put(ReportProgress progressReport)
       at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlResultObject.Put()
       at Microsoft.BDD.Wizards.SCCM_ImportTaskSequenceTask.DoWork(SmsPageData smspageData, Dictionary`2 data)
    Note: previous x86 image was deleted some time ago.
    Please advise.
    J.
    Jan Hoedt

    This is the error in smsprov.log
    *********** WBEM Missing property TransformAnalysisDate    SMS Provider    16/04/2014 15:11:00    7856 (0x1EB0)
    ************ WBEM Missing property TransformReadiness    SMS Provider    16/04/2014 15:11:00    7856 (0x1EB0)
    Image language ID 1033 and en-US    SMS Provider    16/04/2014 15:11:00    7856 (0x1EB0)
    Image language ID 1033 and en-US    SMS Provider    16/04/2014 15:11:10    7856 (0x1EB0)
    Image language ID 1033 and en-US    SMS Provider    16/04/2014 15:11:19    7856 (0x1EB0)
    ERROR> Error -1073741502 returned to execute the command line: "C:\Program Files (x86)\Windows Kits\8.1\Assessment and Deployment Kit\Deployment Tools\amd64\DISM\dism.exe" /Image:"C:\windows\TEMP\BootImages\{8AEF81AB-4B11-4AEF-96D3-E90D84D3DA94}\mount" /Add-Package
    /PackagePath:"C:\Program Files (x86)\Windows Kits\8.1\Assessment and Deployment Kit\Windows Preinstallation Environment\x86\WinPE_OCs\WinPE-Scripting.cab"    SMS Provider    16/04/2014 15:11:19    7856 (0x1EB0)
    Failed to install required components into the boot image C:\windows\TEMP\BootImages\{8AEF81AB-4B11-4AEF-96D3-E90D84D3DA94}\mount    SMS Provider    16/04/2014 15:11:19    7856 (0x1EB0)
    *~*~e:\nts_sccm_release\sms\siteserver\sdk_provider\smsprov\sspbootimagepackage.cpp(3766) : Failed to insert OSD binaries into the WIM file~*~*    SMS Provider    16/04/2014 15:11:36    7856 (0x1EB0)
    *~*~Failed to insert OSD binaries into the WIM file ~*~*    SMS Provider    16/04/2014 15:11:36    7856 (0x1EB0)
    Auditing: User FAC\administrator called an audited method of an instance of class SMS_BootImagePackage.    SMS Provider    16/04/2014 15:11:36    7856 (0x1EB0)
    CExtUserContext::LeaveThread : Releasing IWbemContextPtr=9281008    SMS Provider    16/04/2014 15:11:36    7856 (0x1EB0)
    Jan Hoedt

  • How can I remove pictures from the picture file?

    I have alot of pictures in the picture folder for
    the desktop background and screensaver.
    But there is no option to move to trash or delete.
    And, it won't let you drag them to the trash.
    I would like to remove them, can someone tell me?
    Thanks in advance, John

    jj2327
    You will need follow this progression click on:
    Finder (in dock) -> (Your User Account)-> Pictures,
    when there choose the folders or pictures you want to delete, you can either drag and drop into trash or you can right click and get a drop down menu that will give you the option of "Move to Trash."
    You can choose multiple pictures or files by holding down the Apple Command key and clicking on the ones you want to remove.
    Please report by choosing Yes this helped or No it didn't.
    Good luck,... its easy

  • Moving pictures in the picture well

    I don't want to tag or catalog pictures. I just want to be able to drag and drop or right-click and move pictures (not by the date taken but by how I want them to be arranged before I burn them to a CD). Please tell me how to do this basic operation. Thank you. Angela

    The pictures in the picture well can be arranged in pre-defined sets like Import Batch,Folder location, Date(Newest/Oldest). If you want to move and arrange photos for burning a CD you will have to create a collection. Here is a simple way to do it:
    1. Go to Organize pane and create a collection eg "Burn"
    2. Add the pictures which you want to want to burn, into this collection
    3. Click on this Collection checkbox to view the pictures in this collection
    4. The picutes can be moved in this collection and arranged in whichever way you want.
    Hope this helps.
    Smriti

  • Is it true that Pages cannot insert a page into the middle of a document?

    Is it true that Pages cannot insert a page into the middle of a document?
    I have tried this many times using different techniques and it just refuses to do it. Can anyone help?

    To see how Pages works:
    Menu > View > Page Thumbnails
    When you click on the thumbnails each Section is outlined in yellow.
    Click where you want a new page > Menu > Insert > Section Break
    But then to have a new page all you need to do is add content to fill the page or Insert > Page Break to force the insertion point over onto a new page.
    Peter

  • Iphone 6 camera takes a picture and the picture is missing

    Question about the iphone 6. Two different occasions now i have taken a picture with the stock camera app, the picture shows up in the bottom left preview window and when i go to click it and it takes me to the photo app, the picture is not there. Preview always stays there for the picture but the picture is missing. The first time it happened i tried to reboot the phone, it was still there, then i did a restore  and then the picture preview was finally gone. Now it happened again and i would like to not restore my phone again. Is anyone having this issue? It happened once before the ios8 update and after it. I have been searching all over and cant seem to find anyone who has this problem. I even plugged the phone into my computer to see if it was in there and it wasn't. Thanks!

    Yes  the restore phone worked to lose the pic but then it just happened again a couple weeks later. I actually found a work around for getting rid of the preview picture. I plugged my phone in and deleted any recent pics from the camera and cleared the photo stream then I restored a photo I had from the trash on the phone and then delete the trash photo again, some reason the preview of the lost pic goes away. That just happened on a fluke but I Still haven't figured out why the camera takes a picture and it doesn't always exist except in a preview though. At least i figured out how to get rid of it without restoring.

  • I have Adove Reader XI. All my files have a picture as the first page. I used to be able to see the picture for each file. Now all I see is the PDF logo. How can I change this so I can see the pictures instead of the logo?

    I have Adobe Reader XI. All my files have a picture on the first page. I used to be able to see that picture but now I can only see the PDF logo. How can I change that so I can see the pictures instead of the logo?

    Windows 7

Maybe you are looking for

  • I can't make an animated gif in photoshop cs5

    i followed every step of this tutorial : http://www.youtube.com/watch?v=JKrjTtgJUbE it worked with a lot of people , but when i did it , it looked like this : http://postimg.org/image/h9gzhiuln/ !!! it's really annoying , i imported a video (mp4) fro

  • Can I turn off required passcode in iOS 7.1.1

    There does not seem to be an answer to this in the 7.1 manual and I have not found an answer on the web that was correct or reliable. My simple question: Can the passcode that is used to secure first access to a device running 7.1.1 be disabled? It a

  • Jpanel.getHeight() or getWidth returning 0?

    I am not sure why they are doing that. I initially set the size of the panel to a specific height and width, wouldn't get height and get width return that height or width? My code is below... gameWindow()           super();           JButton button =

  • Loop movie, but load XML once

    Background: I am tasked with building a vertical news scroller that reads from an xml file and loops indefinitely. Problem 1: I have figured out how to scroll static text and I am now working on loading the xml which I also have done. The problem I a

  • Updation of partner address data in sales order

    Hi,    I am trying to create a sales order using an Idoc of the message type ORDERS.    Within this Idoc, the street number for the Sold-to partner is blank.    However, by the time the Idoc is processed and the order is created, the street address