In Word document, there is an option in the insert image dialog box insert button that is "Link to File", where I can input a image url link into the file name input box. Word will then pull that image from the link.
How do i translate that functionality with OpenXML? I'm currently using OpenXml SDK 2.0. My program is suppose to take a word document as input and add an image using that Link to File method
The only difference between how you add a link and how you add an image is in the construction of the relationship. The display part of the image is identical. In order to add the image relationship you'll need something like this:
//This isn't necessery if you know the Part Type (e.g. MainDocumentPart.AddImagePart())
private static ImagePart CreateImagePart(OpenXmlPart container, string contentType)
{
var method = container.GetType().GetMethod("AddImagePart", new Type[] { typeof(string) });
if (method == null)
throw new Exception("Can't add an image to type: " + container.GetType().Name);
return (ImagePart)method.Invoke(container, new object[] { contentType });
}
private static string AddImageToDocument(OpenXmlPart part, string imageSource, string contentType, bool addAsLink)
{
if (addAsLink)
{
ImagePart imagePart = CreateImagePart(part, contentType);
string id = part.GetIdOfPart(imagePart);
part.DeletePart(imagePart);
part.AddExternalRelationship(imagePart.RelationshipType, new Uri(imageSource, UriKind.Absolute), id);
return id;
}
else
{
ImagePart imagePart = CreateImagePart(part, contentType);
using (Stream imageStream = File.Open(imageSource, FileMode.Open))
{
imagePart.FeedData(imageStream);
}
return part.GetIdOfPart(imagePart);
}
}
After you've added the image to the document, you can use the reference show the image
something like...
private static OpenXmlElement CreateImageContainer(OpenXmlPart part, string relationshipId, string imageName, int widthPixels, int heightPixels)
{
long widthEMU = (widthPixels * 914400L) / 96L;
long heightEMU = (heightPixels * 914400L) / 96L;
var element =
new Paragraph(
new Run(
new RunProperties(
new NoProof()),
new Drawing(
new wp.Inline(
new wp.Extent() { Cx = widthEMU, Cy = heightEMU },
new wp.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 0", Description = imageName },
new wp.NonVisualGraphicFrameDrawingProperties(
new a.GraphicFrameLocks() { NoChangeAspect = true }),
new a.Graphic(
new a.GraphicData(
new pic.Picture(
new pic.NonVisualPictureProperties(
new pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = imageName },
new pic.NonVisualPictureDrawingProperties()),
new pic.BlipFill(
new a.Blip() { Embed = relationshipId },
new a.Stretch(
new a.FillRectangle())),
new pic.ShapeProperties(
new a.Transform2D(
new a.Offset() { X = 0L, Y = 0L },
new a.Extents() { Cx = widthEMU, Cy = heightEMU }),
new a.PresetGeometry(
new a.AdjustValueList()
) { Preset = a.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U }))
);
return element;
}
Please note that the final part of this (the CreateImageContainer) I found online and tweaked/renamed/refactored to work for my example and contains an issue, The DocProperties Id and Name and the NonVisualDrawingProperties Id need to be unique throughout the part. (You can't call this method twice in it's current form)
Related
I have a requirement where in I have to parse a DOCX file and extract all the text and images. I am using OpenxmlSDK 2.5 to achieve this. I am able to parse the images and text but the DOCX also have a group of Shapes which I trying to parse and convert them to Drawing images, which is giving me wrong results.
Here is the Sample docx file which I am trying to parse.
I referred the this Stack overflow discussion and tried the same way but no luck.
The resulting DOCX which I am creating with following code is not having any parsed images.
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml;
namespace ReadGroupShape
{
class Program
{
static List<Bitmap> images = new List<Bitmap>();
static void Main(string[] args)
{
MainDocumentPart mainPart = null;
Body content = null;
WordprocessingDocument newDoc = WordprocessingDocument.Create("NewDocx.docx", WordprocessingDocumentType.Document);
MainDocumentPart newMainPart = newDoc.AddMainDocumentPart();
newMainPart.Document = new Document();
Body newbody = newMainPart.Document.AppendChild(new Body());
byte[] docBytes = File.ReadAllBytes("SampleDoc.docx");
using (MemoryStream ms = new MemoryStream())
{
ms.Write(docBytes, 0, docBytes.Length);
using (WordprocessingDocument wpDoc = WordprocessingDocument.Open(ms, true))
{
mainPart = wpDoc.MainDocumentPart;
content = mainPart.Document.Body;
foreach (Paragraph par in content.Descendants<Paragraph>())
{
Paragraph npar = newbody.AppendChild(new Paragraph());
foreach (Run run in par.Descendants<Run>())
{
Run nrun = npar.AppendChild(new Run());
DocumentFormat.OpenXml.Drawing.Blip pic = run.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
ImageData imageData = run.Descendants<ImageData>().FirstOrDefault();
if (pic == null && imageData == null)
{
nrun.InsertAfterSelf(run.CloneNode(true));
}
else
{
if (pic != null)
{
nrun.InsertAfterSelf(CreateImageFromBlip(wpDoc, run, newMainPart, pic));
}
else if (imageData != null)
{
nrun.InsertAfterSelf(CreateImageFromShape(wpDoc, run, newMainPart, imageData));
}
}
}
}
mainPart.Document.Save();
}
}
newMainPart.Document.Save();
newDoc.Close();
}
private static Run CreateImageFromShape(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, ImageData imageData)
{
ImagePart p = sourceDoc.MainDocumentPart.GetPartById(imageData.RelationshipId) as ImagePart;
return CreateImageRun(sourceDoc, sourceRun, mainpart, p);
}
private static Run CreateImageFromBlip(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, DocumentFormat.OpenXml.Drawing.Blip blip)
{
ImagePart newPart = mainpart.AddImagePart(ImagePartType.Png);
ImagePart p = sourceDoc.MainDocumentPart.GetPartById(blip.Embed.Value) as ImagePart;
Bitmap image = new Bitmap(p.GetStream());
using (Stream s = p.GetStream())
{
s.Position = 0;
newPart.FeedData(s);
}
string partId = mainpart.GetIdOfPart(newPart);
Drawing newImage = CreateImage(partId);
return new Run(newImage);
}
private static Run CreateImageRun(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, ImagePart p)
{
ImagePart newPart = mainpart.AddImagePart(ImagePartType.Png);
using (Stream s = p.GetStream())
{
s.Position = 0;
newPart.FeedData(s);
}
string partId = mainpart.GetIdOfPart(newPart);
Drawing newImage = CreateImage(partId);
return new Run(newImage);
}
private static Drawing CreateImage(string relationshipId)
{
// Define the reference of the image.
return new Drawing(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = 990000L, Cy = 792000L },
new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
new DocumentFormat.OpenXml.Drawing.GraphicFrameLocks() { NoChangeAspect = true }),
new DocumentFormat.OpenXml.Drawing.Graphic(
new DocumentFormat.OpenXml.Drawing.GraphicData(
new DocumentFormat.OpenXml.Drawing.Picture(
new DocumentFormat.OpenXml.Drawing.NonVisualPictureProperties(
new DocumentFormat.OpenXml.Drawing.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new DocumentFormat.OpenXml.Drawing.NonVisualPictureDrawingProperties()),
new DocumentFormat.OpenXml.Drawing.BlipFill(
new DocumentFormat.OpenXml.Drawing.Blip(
new DocumentFormat.OpenXml.Drawing.BlipExtensionList(
new DocumentFormat.OpenXml.Drawing.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState =
DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print
},
new DocumentFormat.OpenXml.Drawing.Stretch(
new DocumentFormat.OpenXml.Drawing.FillRectangle())),
new DocumentFormat.OpenXml.Drawing.ShapeProperties(
new DocumentFormat.OpenXml.Drawing.Transform2D(
new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L },
new DocumentFormat.OpenXml.Drawing.Extents() { Cx = 990000L, Cy = 792000L }),
new DocumentFormat.OpenXml.Drawing.PresetGeometry(
new DocumentFormat.OpenXml.Drawing.AdjustValueList()
)
{ Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle }))
)
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
}
}
}
What is that I am missing? Could anyone please help me to parse the shapes and images?
Thanks.
I just started working with Open Xml SDK and I have the following problem. I am trying to replace a text with an image in a word file using Open xml SDK.
The image is on the desired spot but I get the icon " the picture can't be displayed". If I add the image to the end of the document everything works OK. Why is that?
using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(link, true))
{
Text textPlaceHolder = wordDoc1.MainDocumentPart.Document.Body.Descendants<Text>().Where((x) => x.Text == "(Imageplaceholder)").FirstOrDefault();
if (textPlaceHolder == null)
{
Console.WriteLine("Text holder not found!");
}
else
{
var parent = textPlaceHolder.Parent;
if (!(parent is Run)) // Parent should be a run element.
{
Console.Out.WriteLine("Parent is not run");
}
else
{
var element =
new DocumentFormat.OpenXml.Wordprocessing.Drawing(
new DW.Inline(
new DW.Extent() { Cx = 480000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 980000L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "Test.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = "C:\\Users\\Me\\Desktop\\Test.jpg",
CompressionState =
A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
// Insert image (the image created with your function) after text place holder.
textPlaceHolder.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Drawing>(element, textPlaceHolder);
// Remove text place holder.
textPlaceHolder.Remove();
wordDoc1.Close();
}
}
}
Add this to the top of your using block (within the { } ):
using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(link, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
var relationshipId = mainPart.GetIdOfPart(imagePart);
# And then continue with the code you had:
Text textPlaceHolder = wordDoc1.MainDocumentPart.Document.Body.Descendants<Text>().Where((x) => x.Text == "(Imageplaceholder)").FirstOrDefault();
# etc
Then replace your line
Embed = "C:\\Users\\Me\\Desktop\\Test.jpg",
with
Embed = relationshipId,
For future reference:
For me the problem was that I was writing the document to a file before I had disposed of the WordprocessingDocument object.
Either wrap WordprocessingDocument in a using block (like the OP does) or call wordprocessingDocument.Dispose() before you write the document stream to a file.
You've put a path in the Embed property, but it should be the ID of an image part. You'll find how to create this part at the same MSDN URL you've copied the rest from.
I have a task that I have to take go through each slide and input it to a docx file and my condition is that I will not use interop or I can use openXML.
currently i am trying to take image of each slide and insert those images to a document. I got sampleCode from here (with help of spire dll) which produce images of each slide.but the problem is that while creating images the DLL put a watermark at the top of the image (Water Mark Text : Evaluation warning : the docume......) is there any other option to take image of a slide or directly input a slide to a doc file.
and one more thing I can't purchase other license
First: Just pay for the license. The watermark is there for a reason.
To answer your question, an Open XML document is in fact a ZIP file, so it would be quite easy to extract embedded files from there, and even edit them. You just have to extract the file as a ZIP, do your task on them, and zip it again.
You don't need additional libraries to do this, but some may make the zip processing a little easier. If you don't want to use external libraries, you need to use the classes provided under System.IO.Compression.
You can use OpenXML to add image in document, first you need to convert slide to an individual images and then put them one by one
after searching I got following code snippet to insert image in word document
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using Wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using Pic = DocumentFormat.OpenXml.Drawing.Pictures;
namespace GeneratedCode
{
public class GeneratedClass
{
// Creates an Body instance and adds its children.
public Body GenerateBody()
{
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00970886", RsidRunAdditionDefault = "00164292" };
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Drawing drawing1 = new Drawing();
Wp.Inline inline1 = new Wp.Inline(){ DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U };
Wp.Extent extent1 = new Wp.Extent(){ Cx = 2009775L, Cy = 2276475L };
Wp.EffectExtent effectExtent1 = new Wp.EffectExtent(){ LeftEdge = 19050L, TopEdge = 0L, RightEdge = 9525L, BottomEdge = 0L };
Wp.DocProperties docProperties1 = new Wp.DocProperties(){ Id = (UInt32Value)1U, Name = "Picture 0", Description = "Authentication.jpg" };
Wp.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new Wp.NonVisualGraphicFrameDrawingProperties();
A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks(){ NoChangeAspect = true };
graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1);
A.Graphic graphic1 = new A.Graphic();
graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
A.GraphicData graphicData1 = new A.GraphicData(){ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
Pic.Picture picture1 = new Pic.Picture();
picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties();
Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "Authentication.jpg" };
Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties();
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip(){ Embed = "rId6" };
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset(){ X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents(){ Cx = 2009775L, Cy = 2276475L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
graphicData1.Append(picture1);
graphic1.Append(graphicData1);
inline1.Append(extent1);
inline1.Append(effectExtent1);
inline1.Append(docProperties1);
inline1.Append(nonVisualGraphicFrameDrawingProperties1);
inline1.Append(graphic1);
drawing1.Append(inline1);
run1.Append(runProperties1);
run1.Append(drawing1);
paragraph1.Append(run1);
SectionProperties sectionProperties1 = new SectionProperties(){ RsidR = "00970886" };
HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Even, Id = "rId7" };
HeaderReference headerReference2 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = "rId8" };
FooterReference footerReference1 = new FooterReference(){ Type = HeaderFooterValues.Even, Id = "rId9" };
FooterReference footerReference2 = new FooterReference(){ Type = HeaderFooterValues.Default, Id = "rId10" };
HeaderReference headerReference3 = new HeaderReference(){ Type = HeaderFooterValues.First, Id = "rId11" };
FooterReference footerReference3 = new FooterReference(){ Type = HeaderFooterValues.First, Id = "rId12" };
PageSize pageSize1 = new PageSize(){ Width = (UInt32Value)12240U, Height = (UInt32Value)15840U };
PageMargin pageMargin1 = new PageMargin(){ Top = 1440, Right = (UInt32Value)1440U, Bottom = 1440, Left = (UInt32Value)1440U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U };
Columns columns1 = new Columns(){ Space = "720" };
DocGrid docGrid1 = new DocGrid(){ LinePitch = 360 };
sectionProperties1.Append(headerReference1);
sectionProperties1.Append(headerReference2);
sectionProperties1.Append(footerReference1);
sectionProperties1.Append(footerReference2);
sectionProperties1.Append(headerReference3);
sectionProperties1.Append(footerReference3);
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(sectionProperties1);
return body1;
}
}
}
My OpenXML Word document generation project requires text, tables, and images. But first, I need a document header with a logo (image) in it.
I've used the Microsoft example for creating headers and footers at
Generating Documents with Headers and Footers in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office, and text headers work just fine, but the images show up in the header with the broken image icon, a correctly sized border, and the message "This image cannot currently be displayed." Also, I can load the selected image into the document body just fine. Here's how I create the ImagePart:
// Create AG logo part.
_agLogoPart = mainDocumentPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(_agLogoFilename, FileMode.Open))
{
_agLogoPart.FeedData(stream);
}
_agLogoRel = mainDocumentPart.GetIdOfPart(_agLogoPart);
The images are loaded with a LoadImage method, derived from the Microsoft example, but adding parameters for width and height, and returning a Drawing object:
private static Drawing LoadImage(string relationshipId,
string filename,
string picturename,
double inWidth,
double inHeight)
{
double emuWidth = Konsts.EmusPerInch * inWidth;
double emuHeight = Konsts.EmusPerInch * inHeight;
var element = new Drawing(
new DW.Inline(
new DW.Extent { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight },
new DW.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties { Id = (UInt32Value)1U, Name = picturename },
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties { Id = (UInt32Value)0U, Name = filename },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print },
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset { X = 0L, Y = 0L },
new A.Extents { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight }),
new A.PresetGeometry(
new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
return element;
}
Using this, the following code works, loading an image anywhere into the body I want:
Paragraph paraImage = new Paragraph(new Run(LoadImage(_genomeImageRel, _genomeImageFilename, "name" + _genomeImageRel, 7.5, 2.925)));
body.AppendChild(paraImage);
And the following code does not work to put a logo image in the header:
private static Header GeneratePageHeaderPart(string headerText)
{
Header hdr = new Header(new Paragraph(new Run(LoadImage(_agLogoRel, _agLogoFilename, "name" + _agLogoRel, 2.57, 0.73))));
return hdr;
}
I suspect I'm doing something very subtle incorrectly, because I can load the image anywhere but in the header. Can anyone advise?
I suspect I'm doing something very subtle incorrectly, because I can
load the image anywhere but in the header.
If you are able to insert an image into main document, you can also insert an image in header or footer with this code (private static Drawing LoadImage).
The only one difference is where you add the ImagePart:
to insert an image in the body of the document, you add an ImagePart to the MainDocumentPart:
_agLogoPart = mainDocumentPart.AddImagePart(ImagePartType.Jpeg);
...
_agLogoRel = mainDocumentPart.GetIdOfPart(_agLogoPart);
to insert an image in a header, you need add an ImagePart to the HeaderPart that you use to create the header
_agLogoPart = headerPart.AddImagePart(ImagePartType.Jpeg);
...
_agLogoRel = headerPart.GetIdOfPart(_agLogoPart);
to insert an image in a footer, you need add an ImagePart to the FooterPart that you use to create the footer:
_agLogoPart = footerPart.AddImagePart(ImagePartType.Jpeg);
...
_agLogoRel = footerPart.GetIdOfPart(_agLogoPart);
Related:
Insert picture to header of Word document with OpenXML
Please try the following code:
Bitmap image = new Bitmap(imagePath);
SdtElement controlBlock = doc.MainDocumentPart.HeaderParts.First().Header.Descendants<SdtElement>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName).SingleOrDefault();
//find the Blip element of the content control
Blip blip = controlBlock.Descendants<Blip>().FirstOrDefault();
//add image and change embeded id
ImagePart imagePart = doc.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
imagePart.FeedData(stream);
}
blip.Embed = doc.MainDocumentPart.GetIdOfPart(imagePart);
private static MainDocumentPart AddHeader(MainDocumentPart mainDocPart)
{
string LogoFilename = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Images/TemplateLogo.png");
mainDocPart.DeleteParts(mainDocPart.HeaderParts);
var FirstHeaderPart = mainDocPart.AddNewPart<HeaderPart>();
var DefaultHeaderPart = mainDocPart.AddNewPart<HeaderPart>();
var imgPartFirst = FirstHeaderPart.AddImagePart(ImagePartType.Jpeg);
var imagePartFirstID = FirstHeaderPart.GetIdOfPart(imgPartFirst);
var imgPartDefault = FirstHeaderPart.AddImagePart(ImagePartType.Jpeg);
var imagePartDefaultID = FirstHeaderPart.GetIdOfPart(imgPartDefault);
using (FileStream fs = new FileStream(LogoFilename, FileMode.Open))
{
imgPartFirst.FeedData(fs);
}
using (FileStream fsD = new FileStream(LogoFilename, FileMode.Open))
{
imgPartDefault.FeedData(fsD);
}
var rIdFirst = mainDocPart.GetIdOfPart(FirstHeaderPart);
var FirstHeaderRef = new HeaderReference { Id = rIdFirst, Type = HeaderFooterValues.First };
var rIdDefault = mainDocPart.GetIdOfPart(DefaultHeaderPart);
var DefaultHeaderRef = new HeaderReference { Id = rIdDefault };
var sectionProps = mainDocPart.Document.Body.Elements<SectionProperties>().LastOrDefault();
if (sectionProps == null)
{
sectionProps = new SectionProperties();
mainDocPart.Document.Body.Append(sectionProps);
}
sectionProps.RemoveAllChildren<HeaderReference>();
FirstHeaderPart.Header = GenerateFirstPicHeader(imagePartFirstID);
DefaultHeaderPart.Header = GeneratePicHeader(imagePartDefaultID);
FirstHeaderPart.Header.Save();
DefaultHeaderPart.Header.Save();
sectionProps.PrependChild(new TitlePage());
sectionProps.AppendChild(DefaultHeaderRef);
sectionProps.AppendChild(FirstHeaderRef);
return mainDocPart;
}
The word document contains Embedded chart, i want copy and paste same chart int the other document using open xml. I have used Following code but file is being corrupt after pasting chart. Will you please find my mistake?
here doc is my original file WordprocessingDocument object.
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Create("C:\\Sample.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
if (mainPart == null)
{
mainPart = wordprocessingDocument.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
}
var chart = mainPart.AddNewPart<ChartPart>();
chart.FeedData(doc.MainDocumentPart.ChartParts.First().GetStream());
string type = doc.MainDocumentPart.ChartParts.ElementAt(0).EmbeddedPackagePart.ContentType;
var embdedPkgPart = mainPart.AddEmbeddedPackagePart(type);
embdedPkgPart.FeedData(doc.MainDocumentPart.ChartParts.ElementAt(0).EmbeddedPackagePart.GetStream());
string rellId = mainPart.GetIdOfPart(chart);
string uyo = chart.CreateRelationshipToPart(embdedPkgPart);
uyo.ToString();
AddChart(wordprocessingDocument, rellId);
wordprocessingDocument.MainDocumentPart.Document.Save();
}
public static void AddChart(WordprocessingDocument wordDoc, string relId)
{
DocumentFormat.OpenXml.Wordprocessing.Drawing element =
new Drawing(
new Inline(
new Extent()
{
Cx = 5486400,
Cy = 3200400
},
new DW.EffectExtent()
{
LeftEdge = 19050L,
TopEdge = 0L,
RightEdge = 19050L,
BottomEdge = 0L
},
new DocProperties()
{
Id = (UInt32Value)5U,
Name = "Chart 5"
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
new GraphicFrameLocks() { NoChangeAspect = true }),
new Graphic(
new GraphicData(
new DocumentFormat.OpenXml.Drawing.Charts.ChartReference() { Id = relId }
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U
}
);
wordDoc.MainDocumentPart.Document.Body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)));
}
public static void WriteChartParts(MainDocumentPart sourcePart, MainDocumentPart destnPart)
{
var paras = sourcePart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>();
var drawingElements = from run in paras
where run.Descendants<Drawing>().Count() != 0
select run.Descendants<Drawing>().First();
sourcePart.ChartParts.ForAll(chartPart =>
{
destnPart.AddPart<ChartPart>(chartPart, sourcePart.GetIdOfPart(chartPart));
});
drawingElements.ForAll(drw =>
{
destnPart.Document.Body.Append((drw as OpenXmlElement).Clone() as OpenXmlElement);
});
destnPart.Document.Save();
}