Tsu*_*asa 3 c# xml openxml xml-parsing openxml-sdk
下面,我有使用OpenXML在单词的末尾插入图像的代码。我需要做的是尝试在文档中找到名为[Image Holder]的项目,然后将其替换为我要传递的图像。
这是将其添加到文档末尾的当前代码
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "NGSignature"
},
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 = "NGSignature.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationship_id,
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"
});
word_doc.MainDocumentPart.Document.Body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)));
Run Code Online (Sandbox Code Playgroud)
更新 确定,我在OpenXML工具中打开了文件,并发现以下几行包含了我需要在XML文件中替换的数据。
<w:r>
<w:rPr>
<w:sz w:val="20" />
</w:rPr>
<w:instrText xml:space="preserve"> REF NG_MACRO "HOLDER" "3fd95b6f-4c63-42fb-ba2e-dc6d57975c57" </w:instrText>
</w:r>
Run Code Online (Sandbox Code Playgroud)
和
<w:r>
<w:rPr>
<w:sz w:val="20" />
</w:rPr>
<w:t xml:space="preserve">{HOLDER}</w:t>
</w:r>
Run Code Online (Sandbox Code Playgroud)
第二部分是打开文档时看到的内容。第一部分我不确定,但是创建它的应用程序将其放入。
为了正确地做到这一点,我猜想第一部分需要删除,然后图像部分替换第二部分。
要将文本持有人替换为给定的图像,请执行以下步骤:
Drawing元素)插入文本占位符之后。下面的代码实现了上述步骤:
// Search for text holder
Text textPlaceHolder = word_doc.MainDocumentPart.Document.Body.Descendants<Text>()
.Where((x) => x.Text == "$image_tag$").First();
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
{
// Insert image (the image created with your function) after text place holder.
textPlaceHolder.Parent.InsertAfter<Drawing>(element, textPlaceHolder);
// Remove text place holder.
textPlaceHolder.Remove();
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用内容占位符(SdtElement)代替简单的文本占位符。
| 归档时间: |
|
| 查看次数: |
4105 次 |
| 最近记录: |