Cách thêm hình ảnh vào DOCX bằng C++

Trong ví dụ này, chúng ta sẽ tìm hiểu cách thêm hình ảnh vào DOCX bằng C++. Chèn hình ảnh vào văn bản word bằng C++ là một trong những yêu cầu thường gặp của các lập trình viên. Có thể thêm hình ảnh vào DOC bằng C++ bằng các lệnh gọi API đơn giản.

Các bước để thêm hình ảnh trong DOCX bằng C++

  1. Tải xuống và cài đặt gói NuGet Aspose.Words.Cpp mới nhất
  2. Thêm tham chiếu vào không gian tên Aspose::Words
  3. Khởi tạo đối tượng Document Class để tải DOCX để thêm hình ảnh
  4. Khởi tạo lớp DocumentBuilder để làm việc với nội dung bên trong DOCX
  5. Sử dụng phương thức imageWriter để tải và thêm hình ảnh JPEG bên trong tài liệu
  6. Lưu DOCX bằng hình ảnh trong C++ bằng cách sử dụng phương thức Lưu

Trong ví dụ sau, bạn có thể dễ dàng thêm hình ảnh JPEG vào DOCX trong C++ bằng cách sử dụng một số lệnh gọi API và không phụ thuộc bên ngoài vào MS Word. API cho phép bạn thêm hình ảnh JPEG, PNG, GIF hoặc EMF bên trong tài liệu Word.

Mã để thêm hình ảnh trong DOCX bằng C++

#pragma once
#include <cstdint>
#include <iostream>
#include <Aspose.Words.Cpp/Document.h>
#include <Aspose.Words.Cpp/DocumentBase.h>
#include <Aspose.Words.Cpp/DocumentBuilder.h>
#include <Aspose.Words.Cpp/Drawing/Shape.h>
#include <Aspose.Words.Cpp/HeaderFooterType.h>
#include <Aspose.Words.Cpp/Saving/SaveOutputParameters.h>
#include <system/array.h>
#include <system/exceptions.h>
#include <Aspose.Words.Cpp/License.h>
#include <system/io/path.h>
using System::ArrayPtr;
using System::MakeArray;
using System::MakeObject;
using System::SharedPtr;
using System::String;
using namespace Aspose::Words;
using namespace Aspose::Words::Drawing;
class AddContentUsingDocumentBuilder
{
public:
void AddImageinWordDocument()
{
// File name and path of license file
System::String LicenseFileName = u"Aspose.Total.NET.lic";
// Setting the Aspose.Words before creating Word document
SharedPtr<License> wordsLicense = System::MakeObject<License>();
// Setting product license
wordsLicense->SetLicense(LicenseFileName);
// Instantiate Document class to load DOCX and add image
SharedPtr<Document> AddImagesToWordDOC = MakeObject<Document>(u"input.docx");
// Instantiate DocumentBuilder class to work with content inside DOCX
SharedPtr<DocumentBuilder> imageWriter = MakeObject<DocumentBuilder>(AddImagesToWordDOC);
// Take cursor to Primary Header in document
imageWriter->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
// Insert image in word document using C++
SharedPtr<Shape> headerImage = imageWriter->InsertImage(u"Add Image in Word Header.jpg");
// Set Image Size in Header
headerImage->set_Width(1 * 72); // equals to one inch
headerImage->set_Height(1 * 72);
// Save the word document with image to docx format
AddImagesToWordDOC->Save(u"InsertImageinDocx.docx");
}
};

Trước đó, chúng tôi đã xem xét Cách chuyển đổi tài liệu Word thành hình ảnh bằng C++. Trong chủ đề này, chúng ta đã học cách chèn hình ảnh vào tài liệu Word bằng C++.

 Tiếng Việt