I have the following command where I get my notification in ios, I want to get my key more I'm not getting it, what I tried was
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
Messaging.SharedInstance.AppDidReceiveMessage(userInfo);
NSString[] keys = { new NSString("Event_type") };
NSObject[] values = { new NSString("Recieve_Notification") };
var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);
Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);
System.Diagnostics.Debug.WriteLine(userInfo);
// var aps_d = userInfo["aps"] as NSDictionary;
//var alert_d = aps_d["alert"] as NSDictionary;
//var body = alert_d["keys"] as NSString;
}
System.Diagnostics.Debug.WriteLine
receive this
[0:] {
aps = {
alert = {
body = "teste";
title = "teste";
};
};
"gcm.message_id" = "0:1505400569099941%712ac0f8712a1234";
"gcm.n.e" = 1;
"google.c.a.c_id" = 5974019197827881234;
"google.c.a.c_l" = "teste";
"google.c.a.e" = 1;
"google.c.a.ts" = 1505400123;
"google.c.a.udt" = 0;
keys = 152113;
}
keys is a top level and last entry in the dictionary, so you can directly access it via userInfo["keys"], i.e:
var keys = userInfo["keys"] as NSString;
Related
I'm using itext7 for digitally signing the PDF document. below is my scenario:
when a sender send's a PDF document for review (or) signing. we're digitally signing the certificate from our end for security purpose.
when the document from (1) is sent to another sender for signing, the first signer signature is becoming invalid and second signer signature is becoming valid.
we're not showing the digitally signed image.
Code we've written:
public static ConversionJob AddDigitalSignature(string messageId, string keyFilename, string keyFilePassword, string pdfUserPassword, string pdfOwnerPassword, string signatureCreator, string pdfFilename, string outputFilename, bool restrictPdf = false)
{
var encrypt = !string.IsNullOrEmpty(pdfUserPassword) || !string.IsNullOrEmpty(pdfOwnerPassword) || restrictPdf;
outputFilename = !string.IsNullOrEmpty(outputFilename) ? outputFilename : pdfFilename;
var convertJob = new ConversionJob(messageId, "DigitalSignManager.AddDigitalSignature", pdfFilename, outputFilename);
var flattenFile = pdfFilename + ".flatten.pdf";
var encryptedFile = pdfFilename + ".encrypt.pdf";
try
{
_Log.Info("Adding digital signature to file {0} :: [id={1}]", pdfFilename, messageId);
// Remove existing signatures
if (File.Exists(flattenFile))
File.Delete(flattenFile);
ReaderProperties readerOptions = new ReaderProperties();
if (!string.IsNullOrEmpty(pdfOwnerPassword) || restrictPdf)
{
readerOptions.SetPassword(Encoding.ASCII.GetBytes(pdfOwnerPassword));
if (File.Exists(encryptedFile))
File.Delete(encryptedFile);
}
PdfReader reader = new PdfReader(pdfFilename, readerOptions);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(flattenFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
bool hasSignature = form.GetSignatureFlags() > 0;
if (hasSignature)
{
List<string> sigFields = new List<string>();
var fields = form.GetFormFields();
foreach (var field in fields)
{
var formType = field.Value.GetFormType();
if (formType.Equals(PdfName.Sig)) // here's a sig item
{
form.PartialFormFlattening(field.Key);
}
}
form.FlattenFields();
}
//var signFields = form.GetFormFields();
//if (signFields.Keys.Count > 1)
//{
// foreach (var field in signFields)
// {
// var formType = field.Value.GetFormType();
// if (formType.Equals(PdfName.Sig)) // here's a sig item
// {
// form.PartialFormFlattening(field.Key);
// }
// }
// form.FlattenFields();
//}
SignatureUtil signUtil = new SignatureUtil(pdfDoc);
IList<String> names = signUtil.GetSignatureNames();
if (names.Count >= 1)
{
foreach (String name in names)
{
PdfPKCS7 pkcs7 = signUtil.ReadSignatureData(name);
var validity = pkcs7.VerifySignatureIntegrityAndAuthenticity();
var test = signUtil.SignatureCoversWholeDocument(name);
form.PartialFormFlattening(name);
//form.RemoveField(name);
}
form.FlattenFields();
}
if (!pdfDoc.IsClosed())
pdfDoc.Close();
reader.Close();
// reapply password if encrypted
// Sprint S11-119 S11-166 PDF Encryption Start
if (encrypt)
{
var encrypted = Encrypt(messageId, pdfUserPassword, pdfOwnerPassword, flattenFile, encryptedFile, restrictPdf);
convertJob.Encrypted = encrypted.ConvertResult == ConvertResult.Success;
}
// Sprint S11-119 S11-166 PDF Encryption End
// digitally sign the file with certificate
string reason = _Configuration.DigitalSignatureReason; //"Test Electronic Signature";
string location = _Configuration.DigitalSignatureLocation; //"US North America West";
var digitalCert = new DigitalCert(keyFilename, keyFilePassword, true);
var presignPdf = encrypt ? encryptedFile : flattenFile;
PdfReader finalReader = new PdfReader(presignPdf, readerOptions);
StampingProperties sp = new StampingProperties();
sp.UseAppendMode();
PdfSigner signer = new PdfSigner(finalReader, new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite), sp);
// Creating the appearance
Rectangle rect = new Rectangle(0, 0, 0, 0);
PdfSignatureAppearance appearance = signer.GetSignatureAppearance()
//.SetCertificate()
.SetSignatureCreator(signatureCreator)
.SetReason(reason)
.SetLocation(location)
.SetReuseAppearance(false)
.SetPageRect(rect)
.SetPageNumber(1);
//signer.SetFieldName("sig");
signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING);
signer.SetSignDate(DateTime.Now);
// Creating the signature
IExternalSignature pks = new PrivateKeySignature(digitalCert.Akp, digitalCert.DigestAlgorithm);
signer.SignDetached(pks, digitalCert.Chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
finalReader.Close();
// cleanup
if (File.Exists(flattenFile))
File.Delete(flattenFile);
if (File.Exists(encryptedFile))
File.Delete(encryptedFile);
//PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(outputFilename),sp.UseAppendMode());
//PdfAcroForm form1 = PdfAcroForm.GetAcroForm(pdfDoc1, true);
//SignatureUtil signUtil1 = new SignatureUtil(pdfDoc1);
//IList<String> names1 = signUtil1.GetSignatureNames();
//if (names1.Count >= 1)
//{
// foreach (String name in names1)
// {
// PdfPKCS7 pkcs7 = signUtil1.ReadSignatureData(name);
// var validity = pkcs7.VerifySignatureIntegrityAndAuthenticity();
// var test = signUtil1.SignatureCoversWholeDocument(name);
// if (!validity)
// form1.PartialFormFlattening(name);
// }
// form1.FlattenFields();
// if (!pdfDoc1.IsClosed())
// pdfDoc1.Close();
//}
convertJob.SetComplete(ConvertResult.Success);
}
catch (Exception ex)
{
var errorMessage = string.Format("Error adding digital signature to {0}: {1} :: [id={2}]", pdfFilename, ex.Message, messageId);
_Log.Error(ex, FailureType.Conversion, errorMessage);
convertJob.SetComplete(ConvertResult.Failed, errorMessage, ex);
}
return convertJob;
}
the commented code is for removing the not verified signature and adding only the valid signature. But same issue is coming.
i want to POST data to API in my android xamarin app using refit i've tested the API at Postman and it's working fine but at android app i'm getting exception Bad request.
Here is my android code i added the interface and the model i don't know what is the problem .
public interface RequestAPI
{
[Post("/request")]
Task<create_request> submit([Body] create_request request);
}
requestAPI= RestService.For<RequestAPI>("http://courier-magconsulting.azurewebsites.net/api");
button.Click += async delegate
{
try
{
create_request request = new create_request();
request.PickUpPhone = "7664554";
request.DownPayment = 89;
request.DeliveryFees = 56.8;
request.Note = "i need a help!";
request.RequestID = 88; // replace the value yourself
request.DekiveryLocationLatitude = 2323;
request.DeliveryLocationLongitude = 232;
request.PickUpLocationLatitude = 898;
request.PickUpLocationLongitude = 1123;
BroadcastType type = new BroadcastType();
type.Name = "All";
type.ID = 60; // replace the value yourself
request.BroadcastType = type;
Cargosize size = new Cargosize();
size.Name = "Small";
size.ID = 1; // replace the value yourself
request.Cargosize = size;
Cargoweight weight = new Cargoweight();
weight.Name = "Large";
weight.ID = 2; // replace the value yourself
request.CargoWeight = weight;
Sender sender_ = new Sender();
sender_.Name = "Ahmad";
sender_.SenderID = 1; // replace the value yourself
sender_.Phone = "8788";
sender_.SocialID = "8787";
sender_.RatingAvg = 5;
SenderStatus status = new SenderStatus();
status.ID = 1;
status.Name = "Active";
sender_.Senderstatus = status;
request.Sender = sender_;
create_request result = await requestAPI.submit(request);
Toast.MakeText(this, "Request created", ToastLength.Long).Show();
}
catch(Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
};
I'm trying to insert a signature image in a Word document created by a standard-letter generating application. I am using code adapted from various examples found on the web (see below). The application inserts the image, and the space in the document occupied by it is correct, but the image itself is not displayed.
I have tried it with both .png and .jpg images, but neither work; it doesn't appear to be a problem with the image itself.
I have examined the document using the OpenXml SDK Tool, which shows that the image is correctly embedded and encoded as a Base64 data string.
The problem that the SDK Tool does identify is that, compared to a document in which an image is manually inserted (and is correctly displayed), the pic:pic element in the document is rendered with the wrong namespace (a:pic) and it and all child controls are rendered as OpenXmlUnknownElement (see screenshot below).
Can anyone please tell me what is causing the incorrect namespace / element, and how to fix the problem?
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Drawing;
using System.Drawing.Imaging;
...
using A = DocumentFormat.OpenXml.Drawing;
using A14 = DocumentFormat.OpenXml.Office2010.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using WP = DocumentFormat.OpenXml.Wordprocessing;
private void ReplacePlaceholderWithImage(MainDocumentPart mainDocumentPart, OpenXmlElement placeholder, string imagePath)
{
if (placeholder != null)
{
ImagePart ip = AddImagePart(mainDocumentPart, imagePath);
string relationshipId = mainDocumentPart.GetIdOfPart(ip);
var drawing = GetDrawing(relationshipId, imagePath);
placeholder.InsertAfterSelf(new WP.Paragraph(new WP.Run(drawing)));
placeholder.Remove();
Console.WriteLine("Picture inserted into picture content control successfully");
}
}
private ImagePart AddImagePart(MainDocumentPart mainDocumentPart, string imagePath)
{
var partType = GetPartTypeForImage(imagePath);
ImagePart ip = mainDocumentPart.AddImagePart(partType);
using (FileStream fileStream = File.Open(imagePath, FileMode.Open))
{
ip.FeedData(fileStream);
}
return ip;
}
private OpenXmlElement GetDrawing(string relationshipId, string imagePath)
{
//calculate dimensions
var size = GetImageDimensions(imagePath);
// Define the reference of the image.
return
new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = size.Width,
Cy = size.Height
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = Path.GetFileName(imagePath)
},
new PIC.NonVisualPictureDrawingProperties()),
new A.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 A.ShapeProperties(
new A.Transform2D(new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = size.Width, Cy = size.Width }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
}
private ImagePartType GetPartTypeForImage(string imagePath)
{
var img = GetImage(imagePath);
if (img.RawFormat.Equals(ImageFormat.Gif))
{
return ImagePartType.Gif;
}
else if (img.RawFormat.Equals(ImageFormat.Png))
{
return ImagePartType.Png;
}
else if (img.RawFormat.Equals(ImageFormat.Jpeg))
{
return ImagePartType.Jpeg;
}
else
{
throw new ApplicationException("Unexpected image type");
}
}
this issue stressed me up some hours and finally I found the reason. That's because the Drawing element Id need to be unique, you can't fix the ID like this
new DW.DocProperties() { Id = 1U, Name = "Picture 1" }
In my case, I have this function to set alt text and update the Id as well:
private static HashSet<uint> _drawingElementIds = new HashSet<uint>();
public static void SetPictureAltText(OpenXmlElement imageContainer, string altText)
{
var docPro = imageContainer.Descendants<DocProperties>().FirstOrDefault();
if (docPro != null)
{
//Make sure new image has unique ID, otherwise some images won't display
var newId = (uint)new Random().Next(10, 10000);
while (_drawingElementIds.Contains(newId))
{
newId = (uint)new Random().Next(10, 10000);
}
_drawingElementIds.Add(newId);
docPro.Id = new UInt32Value(newId);
docPro.Description = altText;
}
}
Cheers,
Nick
Watch your namespaces! I'm guessing you've copied from the same source as I did (which I'm sure was the Microsoft documentation), however the namespaces appear to be wrong in it for the following two properties:
A.BlipFill -> PIC.BlipFill
A.ShapeProperties -> PIC.ShapeProperties
Full code below:
var element = new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = 5657850L,
Cy = 3771900L
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = "image.png"
},
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 = 5657850L, Cy = 3771900L }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
I recently have a very weird behaviour, so weird I'm starting to wonder if the culprit could be the unit framework I'm using (XUnit). I asked a question about it there: Can Expressmapper copy to destination? but this one is no longer about Expressmapper but about XUnit.
Do you know if in some way XUnit can intefere with the code?
Here's a the reason I'm asking:
I can run those 'together or separatly) in any order and I always get this crazy behaviour:
First test fails (Test_xxx)
Second test pass (Test_Map)
Both tests contain the very same code!!
[Fact]
[Trait("Test kind", "Integration")]
public void Test_xxx()
{
// Arrange
var mapper = new MappingServiceProvider();
mapper.Register<MapSource, MapDestination>();
var src = new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid(),
Parent = new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid()
}
};
src.Children = Enumerable.Range(0, 3).Select(i => new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid()
}).ToList();
var dst = new MapDestination();
// Act
mapper.Map(src, dst);
// Assert
var compare = new CompareLogic(new ComparisonConfig
{
IgnoreObjectTypes = true
});
var comparison = compare.Compare(src, dst);
Assert.Equal(new List<Difference>(), comparison.Differences);
}
[Fact]
[Trait("Test kind", "Integration")]
public void Test_Map()
{
// Arrange
var mapper = new MappingServiceProvider();
mapper.Register<MapSource, MapDestination>();
var src = new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid(),
Parent = new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid()
}
};
src.Children = Enumerable.Range(0, 3).Select(i => new MapSource
{
Id = Guid.NewGuid().GetHashCode(),
Guid = Guid.NewGuid()
}).ToList();
var dst = new MapDestination();
// Act
mapper.Map(src, dst);
// Assert
var compare = new CompareLogic(new ComparisonConfig
{
IgnoreObjectTypes = true
});
var comparison = compare.Compare(src, dst);
Assert.Equal(new List<Difference>(), comparison.Differences);
}
I had another method called Test_Map (with a different signature; aka overload).
I guess XUnit requires method name to be unique (something I intended to do).
I am trying to generate a PowerPoint file containing a image using OpenXML. Unfortunately it does not work. The image is not being displayed. I've checked the file generated with the OpenXML productivity tool and I respectively unzipped the file contents. The file itself contains the image in /ppt/media/image.png and it should be displayed in the second slide.
Here's my code:
private void InsertSlide(string chartString, int position, string title, string text = "")
{
if (m_presentation == null || title == null || m_presentation.PresentationPart == null)
return;
var slide = new Slide(new CommonSlideData(new ShapeTree()));
var nonVisualProperties =
slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
var slidePart = m_presentation.PresentationPart.AddNewPart<SlidePart>();
var imagePart = slidePart.AddImagePart(ImagePartType.Png, "irgendeinscheiss");
//var imageStream = new MemoryStream(Convert.FromBase64String(chartString));
using (var imageStream = new FileStream(#"C:\Users\DA\Desktop\Charts\1_Chart2_01.png", FileMode.Open))
{
imageStream.Position = 0;
imagePart.FeedData(imageStream);
}
slide.Save(slidePart);
var slideIdList = m_presentation.PresentationPart.Presentation.SlideIdList;
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
maxSlideId = slideId.Id;
position--;
if (position == 0)
prevSlideId = slideId;
}
maxSlideId++;
SlidePart lastSlidePart;
if (prevSlideId != null)
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(prevSlideId.RelationshipId);
else
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
if (lastSlidePart.SlideLayoutPart != null)
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
var newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = m_presentation.PresentationPart.GetIdOfPart(slidePart);
m_presentation.PresentationPart.Presentation.Save();
}
Am I missing something? Maybe the relationships? After looking up 232243 thousand different examples, I am still stuck at this point. Thank you!
I think you need to add the image into the slide.CommonSlideData
public Slide InsertSlide(PresentationPart presentationPart, string layoutName)
{
UInt32 slideId = 256U;
// Get the Slide Id collection of the presentation document
var slideIdList = presentationPart.Presentation.SlideIdList;
if (slideIdList == null)
{
throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
}
slideId += Convert.ToUInt32(slideIdList.Count());
// Creates an Slide instance and adds its children.
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
slide.Save(slidePart);
// Get SlideMasterPart and SlideLayoutPart from the existing Presentation Part
SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault
(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));
if (slideLayoutPart == null)
{
throw new Exception("The slide layout " + layoutName + " is not found");
}
slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
slidePart.Slide.CommonSlideData = (CommonSlideData)slideMasterPart.SlideLayoutParts.SingleOrDefault(
sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
// Create SlideId instance and Set property
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
return GetSlideByRelationShipId(presentationPart, newSlideId.RelationshipId);
}
/// <summary>
/// Get Slide By RelationShip ID
/// </summary>
/// <param name="presentationPart">Presentation Part</param>
/// <param name="relationshipId">Relationship ID</param>
/// <returns>Slide Object</returns>
private static Slide GetSlideByRelationShipId(PresentationPart presentationPart, StringValue relationshipId)
{
// Get Slide object by Relationship ID
SlidePart slidePart = presentationPart.GetPartById(relationshipId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
Public void InsertImageInLastSlide(Slide slide, string imagePath, string imageExt)
{
// Creates an Picture instance and adds its children.
P.Picture picture = new P.Picture();
string embedId = string.Empty;
embedId = "rId" + (slide.Elements().Count() + 915).ToString();
P.NonVisualPictureProperties nonVisualPictureProperties = new P.NonVisualPictureProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)4U, Name = "Picture 5" },
new P.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true }),
new ApplicationNonVisualDrawingProperties());
P.BlipFill blipFill = new P.BlipFill();
Blip blip = new Blip() { Embed = embedId };
// Creates an BlipExtensionList instance and adds its children
BlipExtensionList blipExtensionList = new BlipExtensionList();
BlipExtension blipExtension = new BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
UseLocalDpi useLocalDpi = new UseLocalDpi() { Val = false };
useLocalDpi.AddNamespaceDeclaration("a14",
"http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension.Append(useLocalDpi);
blipExtensionList.Append(blipExtension);
blip.Append(blipExtensionList);
Stretch stretch = new Stretch();
FillRectangle fillRectangle = new FillRectangle();
stretch.Append(fillRectangle);
blipFill.Append(blip);
blipFill.Append(stretch);
// Creates an ShapeProperties instance and adds its children.
P.ShapeProperties shapeProperties = new P.ShapeProperties();
A.Transform2D transform2D = new A.Transform2D();
A.Offset offset = new A.Offset() { X = 457200L, Y = 1524000L };
A.Extents extents = new A.Extents() { Cx = 8229600L, Cy = 5029200L };
transform2D.Append(offset);
transform2D.Append(extents);
A.PresetGeometry presetGeometry = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList = new A.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(transform2D);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.AppendChild(picture);
// Generates content of imagePart.
ImagePart imagePart = slide.SlidePart.AddNewPart<ImagePart>(imageExt, embedId);
FileStream fileStream = new FileStream(imagePath, FileMode.Open);
imagePart.FeedData(fileStream);
fileStream.Close();
}
Source Code