Inserir uma imagem em um documento de processamento de texto
Este tópico mostra como utilizar as classes no SDK Open XML para o Office para adicionar programaticamente uma imagem a um documento de processamento de palavras.
Abrir um Documento Existente para Edição
Para abrir um documento existente, instanciar a WordprocessingDocument classe conforme mostrado na seguinte using
instrução. Na mesma instrução, abra o ficheiro de processamento de palavras no especificado filepath
com o Open(String, Boolean) método , com o parâmetro Booleano definido como para true
ativar a edição do documento.
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
Com a v3.0.0+ o Close() método foi removido a favor de depender da instrução using.
Garante que o Dispose() método é chamado automaticamente quando a chaveta de fecho é atingida. O bloco que segue a instrução using estabelece um âmbito para o objeto que é criado ou nomeado na instrução using. Uma vez que a WordprocessingDocument classe no SDK Open XML guarda e fecha automaticamente o objeto como parte da respetiva IDisposable implementação e porque Dispose() é automaticamente chamada quando sai do bloco, não tem de chamar Save() explicitamente ou Dispose() desde que utilize uma using
instrução.
A Representação XML do Objeto Gráfico
O texto seguinte da especificação ISO/IEC 29500 apresenta o elemento Graphic Object Data.
Este elemento especifica a referência a um objeto gráfico no documento. Este objeto gráfico é fornecido inteiramente pelos autores do documento que optam por manter estes dados no documento.
[Nota: dependendo do tipo de objeto gráfico utilizado, nem todas as aplicações geradoras que suportam a arquitetura OOXML terão a capacidade de compor o objeto gráfico. nota de fim]
© ISO/IEC 29500: 2016
O fragmento de Esquema XML seguinte define o conteúdo deste elemento
<complexType name="CT_GraphicalObjectData">
<sequence>
<any minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
</sequence>
<attribute name="uri" type="xsd:token"/>
</complexType>
Como funciona o código de exemplo
Depois de abrir o documento, adicione o ImagePart objeto ao MainDocumentPart objeto através de uma transmissão em fluxo de ficheiros, conforme mostrado no segmento de código seguinte.
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
Para adicionar a imagem ao corpo, defina primeiro a referência da imagem. Em seguida, acrescente a referência ao corpo. O elemento deve estar num Run.
// Define the reference of the image.
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 = "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 = "New Bitmap Image.jpg"
},
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 = 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"
});
if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
Código de exemplo
O exemplo de código seguinte adiciona uma imagem a um documento de palavra existente.
No seu código, pode chamar o InsertAPicture
método ao transmitir o caminho da palavra documento e o caminho do ficheiro que contém a imagem.
Por exemplo, a chamada seguinte insere a imagem.
string documentPath = args[0];
string picturePath = args[1];
InsertAPicture(documentPath, picturePath);
Depois de executar o código, observe o ficheiro para ver a imagem inserida.
Este é o código de exemplo completo em C# e em Visual Basic.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.IO;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
{
if (wordprocessingDocument.MainDocumentPart is null)
{
throw new ArgumentNullException("MainDocumentPart is null.");
}
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
}
}
static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
// Define the reference of the image.
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 = "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 = "New Bitmap Image.jpg"
},
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 = 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"
});
if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}