TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Cibun Swain
NA
257
50.6k
problem in inserting image in imgplace holder of word doc
Oct 21 2013 8:46 AM
Hi i am cibun
i am facing problem while inserting image in
image place holder of word documen
t.
If there is
only one place holder its working fine
. but if there is
more than one images
then
its replacing the first image not the image placeholder
i want urgent help of this problem if anybody has solve this please help me
here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Packaging;
using Microsoft.Office.DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Word = DocumentFormat.OpenXml.Wordprocessing;
using ClientOM = Microsoft.SharePoint.Client;
using Microsoft.Office.Word.Server.Conversions;
using System.Threading;
namespace DocxImages
{
class Program
{
static string siteUrl = "http://na03:33669";
static void Main(string[] args)
{
using (SPSite spSite = new SPSite(siteUrl))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPList DocList = spWeb.Lists["LibSignature"];
SPListItem doc_item = DocList.GetItemById(1);
SPFile doc_inputFile = doc_item.File;
string outputPath = string.Format(@"/{0}/{1}", DocList.RootFolder.Url, doc_inputFile.Name);
byte[] byteArray2 = doc_inputFile.OpenBinary();
DocxImageProcessor docxImageProcessor = new DocxImageProcessor();
docxImageProcessor.UpdateImagePlaceHolder("Signimage", byteArray2);
}
}
}
}
public class DocxImageProcessor
{
string outputPath1;
MemoryStream memOut = null;
string siteUrl = "http://na03:33669";
MainDocumentPart m_mainDocPart;
WordprocessingDocument m_wordProcessingDocument;
Package m_docxPackage;
XmlDocument m_mainXmlDocument;
PackagePart m_masterDocumentPart = null;
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const string imageRelType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
public DocxImageProcessor()
{
using (SPSite spSite = new SPSite(siteUrl))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPList DocList = spWeb.Lists["MergeDocSig"];
SPListItem doc_item = DocList.GetItemById(50);
SPFile doc_inputFile = doc_item.File;
outputPath1 = string.Format(@"/{0}/{1}", DocList.RootFolder.Url, doc_inputFile.Name);
byte[] byteArray2 = doc_inputFile.OpenBinary();
// In-memory stream for our consolidated WSR DOCX.
memOut = new MemoryStream();
memOut.Write(byteArray2, 0, (int)byteArray2.Length);
// string docxPath = "template.docx";
m_wordProcessingDocument = WordprocessingDocument.Open(memOut, true);
m_mainDocPart = m_wordProcessingDocument.MainDocumentPart;
m_mainXmlDocument = DocxComponentsProvider.GetDocxXmlDocument(m_mainDocPart.GetStream());
m_masterDocumentPart = DocxComponentsProvider.GetMainDocumentPart(m_wordProcessingDocument);
m_docxPackage = m_wordProcessingDocument.Package;
}
}
}
public void UpdateImagePlaceHolder(string imagePlaceHolderTagName, byte[] m_imageInBytes)
{
string imageRelationshipId = GetImagePlaceHolderRelationShipId(imagePlaceHolderTagName);
if (imageRelationshipId != string.Empty)
{
//Look through the documents relationships to see if there is an image.
PackageRelationship imagePartRelation = m_masterDocumentPart.GetRelationship(imageRelationshipId);
if (imagePartRelation != null && imagePartRelation.RelationshipType == imageRelType)
{
Uri imageUri = PackUriHelper.ResolvePartUri(m_masterDocumentPart.Uri, imagePartRelation.TargetUri);
PackagePart masterImagePart = m_docxPackage.GetPart(imageUri);
if (masterImagePart != null)
{
using (Stream outputStream = masterImagePart.GetStream(FileMode.Open, FileAccess.Write))
{
outputStream.Write(m_imageInBytes, 0, m_imageInBytes.Length);
}
masterImagePart.Package.Flush();
}
}
}
m_docxPackage.Flush();
DocxImageProcessor obj = new DocxImageProcessor();
memOut.Seek(0, SeekOrigin.Begin);
ClientContext clientContext = new ClientContext(siteUrl);
ClientOM.File.SaveBinaryDirect(clientContext, obj.outputPath1, memOut, true);
#region MyRegion2
using (SPSite spSite = new SPSite(siteUrl))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
string docPath = string.Format(@"{0}{1}", spSite.Url.Replace(@"\\", ""), obj.outputPath1);
string pdfPath = docPath.Replace(".docx", ".pdf");
ConversionJobSettings JobSettings = new ConversionJobSettings();
JobSettings.OutputFormat = SaveFormat.PDF;
JobSettings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
ConversionJob ConvJob = new ConversionJob("Word Automation Services", JobSettings);
ConvJob.UserToken = spSite.UserToken;
ConvJob.AddFile(docPath, pdfPath);
ConvJob.Start();
Console.WriteLine("Conversion job started");
ConversionJobStatus status = new ConversionJobStatus("Word Automation Services", ConvJob.JobId, null);
Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
while (true)
{
Thread.Sleep(5000);
status = new ConversionJobStatus("Word Automation Services", ConvJob.JobId,
null);
if (status.Count == status.Succeeded + status.Failed)
{
Console.WriteLine("Completed, Successful: {0}, Failed: {1}", status.Succeeded, status.Failed);
break;
}
Console.WriteLine("In progress, Successful: {0}, Failed: {1}", status.Succeeded, status.Failed);
}
#endregion
}
}
}
private string GetImagePlaceHolderRelationShipId(string imagePlaceHolderTagName)
{
string searchString = StringUtil.GetConcatenatedString("//w:sdt//w:sdtPr//w:tag[@w:val='", imagePlaceHolderTagName,"']");
XPathNodeIterator xpathNodeIterator = XMLUtil.GetNodesUsingNameSpace(searchString, m_mainXmlDocument);
string imageRelationshipId = string.Empty;
if (xpathNodeIterator != null && xpathNodeIterator.Count > 0)
{
xpathNodeIterator.Current.MoveToParent();
xpathNodeIterator.Current.MoveToParent();
XPathNodeIterator xpathNodeIteratorForRelationShipId = xpathNodeIterator.Current.SelectDescendants(DocxWordXmlConstants.DOCX_DRAWINGML_BLIP,
DocxWordXmlConstants.DRAWINGMLNAMESPACE, false);
if (xpathNodeIteratorForRelationShipId != null || xpathNodeIteratorForRelationShipId.Count > 0)
{
while (xpathNodeIteratorForRelationShipId.MoveNext())
{
if (xpathNodeIteratorForRelationShipId.Current.Name == DocxWordXmlConstants.DOCX_DRAWINGML_PREFIX_BLIP)
{
xpathNodeIteratorForRelationShipId.Current.MoveToFirstAttribute();
imageRelationshipId = xpathNodeIteratorForRelationShipId.Current.Value;
break;
}
}
}
}
return imageRelationshipId;
}
}
internal class DocxComponentsProvider
{
public static PackagePart GetMainDocumentPart(WordprocessingDocument wordProcessingDoc)
{
//Get the main document part of the master docx (document.xml).
PackagePart masterDocumentPart = null;
foreach (PackageRelationship masterDocumentRelationship in GetPackageRelationshipsFromDocx(wordProcessingDoc, DocxWordXmlConstants.DOCUMENT_RELATIONSHIP))
{
Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), masterDocumentRelationship.TargetUri);
masterDocumentPart = wordProcessingDoc.Package.GetPart(documentUri);
break;
}
return masterDocumentPart;
}
private static IEnumerable<PackageRelationship> GetPackageRelationshipsFromDocx(WordprocessingDocument wordDoc,
string relationshipType)
{
//e.g. relationshipType for document xml "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
foreach (PackageRelationship packageRelationship in wordDoc.Package.GetRelationshipsByType(relationshipType))
{
//yield Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.
yield return packageRelationship;
}
}
///<summary>
/// Returns the XmlDocument of the specified docx stream
///</summary>
///<history>
///</history>
///<usage>
///XmlDocument xmlDoc = XMLUtil.GetDocxXmlDocument (docxStream);
///</usage>
public static XmlDocument GetDocxXmlDocument(Stream docxStream)
{
XmlDocument mainXmlDocument = null;
if (docxStream == Stream.Null)
{
return mainXmlDocument;
}
//Create XML document and load the *.DOCX
mainXmlDocument = new XmlDocument();
mainXmlDocument.Load(docxStream);
return mainXmlDocument;
}
}
public class StringUtil
{
public static string GetConcatenatedString(params string[] stringArray)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (string stringInArray in stringArray)
stringBuilder.Append(stringInArray);
return stringBuilder.ToString();
}
}
internal class XMLUtil
{
/// <summary>
/// This function returns the XPathNodeIterator containing the list of nodes satisfying the
/// criteria as specified in the searchString. Uses XPath.
/// </summary>
/// <param name="xPath"></param>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public static XPathNodeIterator GetNodesUsingNameSpace(string searchString, XmlDocument xmlDocument)
{
if (xmlDocument == null || searchString.Length == 0)
return null;
XPathNodeIterator iterator = null;
XPathNavigator navigator = xmlDocument.CreateNavigator();
XPathExpression expression = navigator.Compile(searchString);
XmlNamespaceManager xmlNamespaceManager = XMLUtil.CreateXmlNamespaceManager();
iterator = navigator.Select(searchString, xmlNamespaceManager);
return iterator;
}
///<summary>
/// This function creates collection of name space URI's and prefixes which are beign used
///</summary>
///<history>
///</history>
public static XmlNamespaceManager CreateXmlNamespaceManager()
{
XmlNamespaceManager xmlNamespaceManager = null;
NameTable nameTable = new NameTable();
xmlNamespaceManager = new XmlNamespaceManager(nameTable);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_WORDML_PREFIX, DocxWordXmlConstants.WORDMLNAMESPACE);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_WORDPROCESSINGDRAWING_PREFIX, DocxWordXmlConstants.WORDPROCESSINGDRAWING);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_DRAWINGML_PREFIX, DocxWordXmlConstants.DRAWINGMLNAMESPACE);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_DRAWINGMLPICTURE_PREFIX, DocxWordXmlConstants.DRAWINGMLPICTURENAMESPACE);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_WORDML_RELATIONSHIP, DocxWordXmlConstants.RELATIONSHIPNAMESPACE);
xmlNamespaceManager.AddNamespace(DocxWordXmlConstants.DOCX_URN_SCHEMAS_MS_COM_VML, DocxWordXmlConstants.URN_SCHEMAS_MS_COM_VML);
xmlNamespaceManager.AddNamespace("ds", "http://schemas.openxmlformats.org/officedocument/2006/2/customXml");
return xmlNamespaceManager;
}
}
public class DocxWordXmlConstants
{
public const string WORDMLNAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
public const string OPENXMLPATH = "http://schemas.openxmlformats.org/officeDocument/";
public const string DRAWINGMLNAMESPACE = "http://schemas.openxmlformats.org/drawingml/2006/main";
public const string WORDPROCESSINGDRAWING = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
public const string DRAWINGMLPICTURENAMESPACE = "http://schemas.openxmlformats.org/drawingml/2006/picture";
public const string RELATIONSHIPNAMESPACE = OPENXMLPATH + "2006/relationships";
public const string DOCUMENT_RELATIONSHIP = OPENXMLPATH + "2006/relationships/officeDocument";
public const string IMAGE_RELATIONSHIP = OPENXMLPATH + "2006/relationships/image";
public const string URN_SCHEMAS_MS_COM_VML = "urn:schemas-microsoft-com:vml";
//public const string IMAGE_CONTENT_TYPE = "image/png";
// public const string IMAGE_URI_STRING = "/word/media/";
public const string DOCX_WORDML_PREFIX = "w";
public const string DOCX_DRAWINGML_PREFIX = "a";
public const string DOCX_WORDPROCESSINGDRAWING_PREFIX = "wp";
public const string DOCX_DRAWINGMLPICTURE_PREFIX = "pic";
public const string DOCX_URN_SCHEMAS_MS_COM_VML = "v";
public const string DOCX_WORDML_BOLD = "b";
public const string DOCX_WORDML_ON = "on";
public const string DOCX_WORDML_XML = "xml";
public const string DOCX_WORDML_SPACE = "space";
public const string DOCX_WORDML_PRESERVE = "preserve";
public const string DOCX_WORDML_TYPE = "type";
public const string DOCX_WORDML_SHADE = "shd";
public const string DOCX_WORDML_ALIGNMENT = "jc";
public const string DOCX_WORDML_COLOR = "color";
public const string DOCX_WORDML_FILL = "fill";
public const string DOCX_WORDML_BACKGROUND_COLOR = "bgcolor";
public const string DOCX_WORDML_SIZE = "sz";
public const string DOCX_WORDML_AUXILIARY = "wx";
public const string DOCX_WORDML_TOP = "top";
public const string DOCX_WORDML_LEFT = "left";
public const string DOCX_WORDML_BOTTOM = "bottom";
public const string DOCX_WORDML_RIGHT = "right";
public const string DOCX_WORDML_SINGLE = "single";
public const string DOCX_WORDML_AUTO = "auto";
public const string DOCX_WORDML_CANTSPLIT = "cantSplit";
public const string DOCX_WORDML_VALIGN = "vAlign";
public const string DOCX_WORDML_VERTICAL_ALIGN = "vertAlign";
public const string DOCX_WORDML_SUPERSCRIPT = "superscript";
public const string DOCX_DRAWINGML_BLIP = "blip"; // Node which holds image relationship id
public const string DOCX_DRAWINGML_PREFIX_BLIP = DOCX_DRAWINGML_PREFIX + ":" + DOCX_DRAWINGML_BLIP;
// RELATIONSHIP
public const string DOCX_WORDML_RELATIONSHIP = "r";
public const string DOCX_WORDML_RELATIONSHIP_PROPERTY = "rPr";
public const string DOCX_RELATIONSHIP_EMBED = "embed";// Attribute which holds image relationship id
public const string DOCX_RELATIONSHIP_PREFIX_EMBED = DOCX_WORDML_RELATIONSHIP + ":" + DOCX_RELATIONSHIP_EMBED;
// BODY
public const string DOCX_WORDML_BODY = "body";
public const string DOCX_WORDML_PREFIX_BODY = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_BODY;
// BOOKMARK
public const string DOCX_WORDML_BOOKMARKSTART = "bookmarkStart";
public const string DOCX_WORDML_PREFIX_BOOKMARKSTART = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_BOOKMARKSTART;
// NAME
public const string DOCX_WORDML_NAME = "name";
public const string DOCX_WORDML_PREFIX_NAME = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_NAME;
// VAL
public const string DOCX_WORDML_VAL = "val";
public const string DOCX_WORDML_PREFIX_VAL = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_VAL;
public const string DOCX_WORDML_NUMPR = "numPr";
public const string DOCX_WORDML_PREFIX_NUMPR = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_NUMPR;
// TABLE
public const string DOCX_WORDML_TABLE = "tbl";
public const string DOCX_WORDML_TABLE_PROPERTY = "tblPr";
public const string DOCX_WORDML_TABLE_STYLE = "tblStyle";
public const string DOCX_WORDML_TABLE_LOOK = "tblLook";
public const string DOCX_WORDML_TABLE_WIDTH = "tblW";
public const string DOCX_WORDML_TABLE_INDENT = "tblInd";
public const string DOCX_WORDML_TABLE_LAYOUT = "tblLayout";
public const string DOCX_WORDML_TABLE_OVERLAP = "tblOverlap";
public const string DOCX_WORDML_TABLE_BORDERS = "tblBorders";
public const string DOCX_WORDML_TABLE_COLUMN_DEFINITIONS = "tblGrid";
public const string DOCX_WORDML_TABLE_COLUMN_WIDTH = "gridCol";
public const string DOCX_WORDML_TABLE_ROW = "tr";
public const string DOCX_WORDML_TABLE_ROW_PROPERTY = "trPr";
public const string DOCX_WORDML_TABLE_HEADER = "tblHeader";
public const string DOCX_WORDML_TABLE_CELL = "tc";
public const string DOCX_WORDML_TABLE_CELL_PROPERTY = "tcPr";
public const string DOCX_WORDML_TABLE_CELL_WIDTH = "tcW";
public const string DOCX_WORDML_PREFIX_TABLE = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_TABLE;
public const string DOCX_WORDML_PREFIX_RELATIONSHIP = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_RELATIONSHIP;
public const string DOCX_WORDML_TABLE_PROPERTY_TBLLOOK_VAL = "01E0";//The tblLook element contains a bitmask that specifies how rows are to be formatted. The hexadecimal value "01E0" is the result of summing the values for four options: header row formatting, last row formatting, header column formatting, and last column formatting.
// TEXT
public const string DOCX_WORDML_TEXT = "t";
public const string DOCX_WORDML_PREFIX_TEXT = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_TEXT;
// PARAGRAPH
public const string DOCX_WORDML_PARAGRAPH = "p";
public const string DOCX_WORDML_PREFIX_PARAGRAPH = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_PARAGRAPH;
public const string DOCX_WORDML_PARAGRAPH_PROPERTY = "pPr";
public const string DOCX_WORDML_PREFIX_PARAGRAPH_PROPERTY = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_PARAGRAPH_PROPERTY;
public const string DOCX_WORDML_PARAGRAPH_STYLE = "pStyle";
public const string DOCX_WORDML_PREFIX_PARAGRAPH_STYLE = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_PARAGRAPH_STYLE;
// BREAK
public const string DOCX_WORDML_BREAK = "br";
public const string DOCX_WORDML_PREFIX_BREAK = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_BREAK;
public const string DOCX_WORDML_BREAK_PROPERTY_TYPE = DOCX_WORDML_PREFIX + ":" + DOCX_WORDML_TYPE;
public const string DOCX_WORDML_BREAK_PROPERTY_VAL = "page";
public const string STATIC_REGION_BLOCK = "STATIC_REGION_BLOCK";
public const string STATIC_REGION_TAG = "STATIC_REGION_TAG";
public const string HTML_BOLD_START_TAG = "<b>";
public const string HTML_BOLD_END_TAG = "</b>";
public const string TABLE_COLUMN_ATTRIBUTE_NAME_WIDTH = "WIDTH";
public const string TABLE_COLUMN_ATTRIBUTE_NAME_FILL = "FILL";
public const string TABLE_COLUMN_ATTRIBUTE_NAME_STYLE = "STYLE";
public const string DOCX_WORDML_VERT_ALIGN = "vertAlign";
public const string DOCX_WORDML_VERT_ALIGN_SUPERSCRIPT = "superscript";
}
}
regards
cibun swain
8125305463
[email protected]
Reply
Answers (
0
)
.NET / SharePoint
Customization of QuickLaunchbar in sharepoint2013