このチュートリアルでは、C#を使用してワードドキュメントに画像を追加する方法を段階的に説明します。 C#のコマンドラインアプリケーションを使用して、Word文書に画像を追加します。
C#を使用してWord文書に画像を追加する手順
- ソリューション内のSystem.Drawingアセンブリへの参照を追加します
- 次に、Aspose.Words for .NETNuGetパッケージ参照を追加する必要があります
- Aspose.WordsおよびAspose.Words.Drawing名前空間のusingディレクティブを追加します
- License.SetLicenseメソッドを呼び出す
- ドキュメントオブジェクトを作成して、ファイルシステムまたはメモリストリームからWordDOCをロードします
- テキスト、画像、表などを書き込むためのDocumentBuilderクラスオブジェクトを作成します。
- カーソルをヘッダーまたはフッター、あるいはWordDOCの任意の位置に移動します
- DocumentBuilder.InsertImageを使用して、ストリームまたはファイルから画像を追加します
- Shape classを使用して、画像のサイズ、位置、塗りつぶしなどをさらに設定します
- Document.Saveメソッドを呼び出して、WordDOCをディスクまたはストリームに保存します
.NETアプリケーションで次のコード例を使用して、C#を使用してWord文書に画像を追加できます。
C#を使用してWord文書に画像を追加するコード
using Aspose.Words; | |
using Aspose.Words.Drawing; | |
namespace HowtoAddImageinWordDocumentUsingCsharp | |
{ | |
class AddImageToWordDOC | |
{ | |
static void Main(string[] args) | |
{ | |
// Set license prior to adding image in Word document using C# | |
License setupPriorAddingImages = new License(); | |
setupPriorAddingImages.SetLicense("path to license.lic"); | |
// Load Word DOC document that you want to add images to | |
Document AddImagesToWordDOC = new Document("input.doc"); | |
// Instantiate DocumentBuilder class object to write text, images, tables etc. | |
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC); | |
// Move cursor to Primary Header in Word DOC | |
imageWriter.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary); | |
// Insert image in word document header c# | |
Shape headerImage = imageWriter.InsertImage("C:\\Add Image in Word Header.jpg"); | |
// Set Image Size in Header | |
headerImage.Width = 1 * 72; // equals to one inch | |
headerImage.Height = 1 * 72; | |
// Now, move cursor to last Paragraph in Word Document | |
imageWriter.MoveTo(AddImagesToWordDOC.LastSection.Body.LastParagraph); | |
// Add Image to Word Document and Link to File | |
Shape imageAsLinkToFile = imageWriter.InsertImage("C:\\Add Image as Link to File.jpg"); | |
imageAsLinkToFile.ImageData.SourceFullName = "C:\\Add Image as Link to File.jpg"; | |
// Save As DOCX | |
AddImagesToWordDOC.Save("C:\\Word with Embeded and Linked Images.docx"); | |
} | |
} | |
} |
したがって、上記のVisual Studioアプリケーションを使用すると、Word文書C#に画像を追加できます。既存のDOCファイルをロードしますが、プログラムでC#でWord文書を作成するすることもできます。このコードは、Word DOC C#に画像を追加する2つの方法を示しています。最初にWordドキュメントヘッダーC#に画像を挿入し、次にリンクされた画像として画像をWordに追加します。つまり、この場合の画像は埋め込まれていませんが、ファイルへのリンクとして挿入されます。