C++: Change Page Margins in Word

Page margins are the blank spaces at the top, bottom, left, and right edges of a document page. In Word, it may sometimes be quite necessary to adjust the margins to meet the layout requirements of specific documents, such as academic papers, business reports, or creative projects. This article will demonstrate how to programmatically change the page margins of an existing Word document using Spire.Doc for C++.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Set Page Margins in Word in C++

The MarginsF class provided by Spire.Doc for C++ represents the page margins in Word. To set or change the margins of a Word document, you can use the methods of MarginsF class. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Get a specified section using Document->GetSections()->GetItemInSectionCollection() method.
  • Get the page margins of the section using Section->GetPageSetup()->GetMargins() method.
  • Set the top, bottom, left and right margins for the pages in the section using MarginsF->SetTop(), MarginsF->SetBottom(), MarginsF->SetLeft(), MarginsF->SetRight() methods.
  • Save the result document using Document.SaveToFile() method.
  • C++
#include "Spire.Doc.o.h"

using namespace std;
using namespace Spire::Doc;

int main() {
	//Specify the input and output file paths
	wstring inputFile = L"Data\\Foods.docx";
	wstring outputFile = L"SetMargins.docx";

	//Create a Document instance
	intrusive_ptr<Document> document = new Document();

	//Load a Word document
	document->LoadFromFile(inputFile.c_str());

	//Get the first section
	intrusive_ptr<Section> section = document->GetSections()->GetItemInSectionCollection(0);

	//Set top, bottom, left and right page margins for the section 
	section->GetPageSetup()->GetMargins()->SetTop(38.0f);
	section->GetPageSetup()->GetMargins()->SetBottom(38.0f);
	section->GetPageSetup()->GetMargins()->SetLeft(29.5f);
	section->GetPageSetup()->GetMargins()->SetRight(29.5f);

	//Save the result document
	document->SaveToFile(outputFile.c_str(), FileFormat::Docx2016);
	document->Close();
}

C++: Change Page Margins in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.