ワープロ ドキュメントに画像を挿入する
このトピックでは、Open XML SDK for Office のクラスを使用して、プログラムによってワープロ ドキュメントに画像を追加する方法について説明します。
既存のドキュメントを編集用に開く
既存のドキュメントを開くには、次の using
ステートメントに示すように、WordprocessingDocument クラスをインスタンス化します。 同じステートメントで、Open(String, Boolean) メソッドを使用して、指定したfilepath
でワープロ ファイルを開き、Boolean パラメーターを true
に設定してドキュメントの編集を有効にします。
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
v3.0.0 以降では、using ステートメントに依存することを優先して、Close() メソッドが削除されました。
これにより、閉じかっこに達したときに、 Dispose() メソッドが自動的に呼び出されます。 using ステートメントに続くブロックは、using ステートメントで作成または名前付けされたオブジェクトのスコープを確立します。 Open XML SDK の WordprocessingDocument クラスは、IDisposable実装の一部としてオブジェクトを自動的に保存および閉じます。また、ブロックを終了するとDispose()が自動的に呼び出されるため、using
ステートメントを使用する限り、明示的にSave()またはDispose()を呼び出す必要はありません。
グラフィック オブジェクトの XML 表現
グラフィック オブジェクト データ要素は、ISO/IEC 29500 仕様書で導入され、次のように説明されています。
この要素は、ドキュメント内のグラフィック オブジェクトへの参照を指定します。 このグラフィック オブジェクトは、そのデータをドキュメント内に保持することを選択したドキュメントの作成者によってのみ提供されます。
[注意: 使用されるグラフィック オブジェクトの種類によっては、OOXML フレームワークをサポートする生成側アプリケーションの一部でそのグラフィック オブジェクトをレンダリングできない場合があります。 メモの終了]
© ISO/IEC 29500: 2016
次の XML スキーマ フラグメントは、この要素のコンテンツを定義しています。
<complexType name="CT_GraphicalObjectData">
<sequence>
<any minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
</sequence>
<attribute name="uri" type="xsd:token"/>
</complexType>
サンプル コードの動作のしくみ
ドキュメントを開いたら、次のコード セグメントに示すように、ファイル ストリームを使用してMainDocumentPart オブジェクトにImagePart オブジェクトを追加します。
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));
本文にイメージを追加するには、最初にイメージの参照を定義します。 次に、その参照を本文に追加します。 要素は、 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)));
サンプル コード
次のコード例では、既存の Word 文書に画像を追加しています。
コードでは、文書という単語のパスと画像を含むファイルのパスを渡すことで、 InsertAPicture
メソッドを呼び出すことができます。
たとえば、次の呼び出しでは画像が挿入されます。
string documentPath = args[0];
string picturePath = args[1];
InsertAPicture(documentPath, picturePath);
コードを実行した後、ファイルを見て、挿入された画像を確認します。
以下に、C# と 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)));
}