บทช่วยสอนนี้จะแนะนำคุณทีละขั้นตอนเกี่ยวกับวิธีเพิ่มรูปภาพในเอกสารคำโดยใช้ C# เราจะใช้แอปพลิเคชันบรรทัดคำสั่งใน C# เพิ่มรูปภาพลงในเอกสารคำ
ขั้นตอนในการเพิ่มรูปภาพในเอกสาร Word โดยใช้ C#
- เพิ่มการอ้างอิงถึงแอสเซมบลี System.Drawing ในโซลูชัน
- ถัดไป ต้องเพิ่มการอ้างอิงแพ็กเกจ Aspose.Words for .NET NuGet
- เพิ่มโดยใช้คำสั่งสำหรับ Aspose.Words และ Aspose.Words.Drawing เนมสเปซ
- โทร License.SetLicense วิธีการ
- สร้างวัตถุเอกสารเพื่อโหลด Word DOC จากระบบไฟล์หรือสตรีมหน่วยความจำ
- สร้างวัตถุคลาส DocumentBuilder เพื่อเขียนข้อความ รูปภาพ ตาราง ฯลฯ
- เลื่อนเคอร์เซอร์ไปที่ Header หรือ Footer หรือตำแหน่งที่ต้องการใน Word DOC
- ใช้ DocumentBuilder.InsertImage เพื่อเพิ่มรูปภาพจากสตรีมหรือไฟล์
- ใช้ Shape class เพื่อกำหนดขนาด ตำแหน่ง การเติม ฯลฯ ของรูปภาพเพิ่มเติม
- โทร Document.Save วิธีบันทึก Word DOC ลงดิสก์หรือสตรีม
คุณสามารถใช้ตัวอย่างโค้ดต่อไปนี้ในแอปพลิเคชัน .NET เพื่อเพิ่มรูปภาพในเอกสาร Word โดยใช้ C#
รหัสเพื่อเพิ่มรูปภาพในเอกสาร Word โดยใช้ C
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 ข้างต้นจะอนุญาตให้คุณเพิ่มรูปภาพลงในเอกสารคำ C# มันโหลดไฟล์ DOC ที่มีอยู่ แต่คุณสามารถ สร้างเอกสารคำใน C# โดยทางโปรแกรมได้ รหัสนำเสนอสองวิธีในการเพิ่มรูปภาพใน word DOC C# - ขั้นแรกให้แทรกรูปภาพในส่วนหัวของเอกสาร word C# แล้วจึงเพิ่มรูปภาพใน word เป็นภาพที่มีการเชื่อมโยง กล่าวคือรูปภาพในกรณีนี้ไม่ได้ถูกฝัง แต่ถูกแทรกเป็นลิงก์ไปยังไฟล์