Monday, 03 April 2023 01:15

C++: Protect or Unprotect Word Documents

Document security is particularly important when critical or private data is involved in a Word document. There are several security options in Word that you can use to protect your documents, including password protection, read-only mode, editing restrictions, and partial protection. On the contrary, when the protection is no longer required, you may need to unprotect a Word document to improve work efficiency.

In this article, you will learn how to protect or unprotect Word documents in C++ 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

Password Protect a Word Document in C++

Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Encrypt the document with a password using Document->Eencrypt(LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample.docx");

    //Encrypt the document with a password
    document->Encrypt("open-psd");

    //Save the document to another Word file
    document->SaveToFile("Output/Encryption.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Restrict Editing of a Word Document in C++

If you want to grant people permission to read your document but restrict the types of modifications that someone can make, you can protect your document with a specific protection type and a permission password.

Protection Type Description
AllowOnlyComments Modification of comments in the document is allowed.
AllowOnlyFormFields The user can only enter data in the form fields in the document.
AllowOnlyReading The document is read-only.
AllowOnlyRevisions The user can only add revision marks to the document.
NoProtection The document is not protected.

The following are the steps to restrict editing of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Protect the document by specifying the protection type and the permission password using Document->Protect(Spire::Doc::ProtectionType type, LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/ProtectionType.h"
using namespace std;
using namespace Spire::Doc;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample.docx");

    //Protect the document by specifying the protection type and the password
    document->Protect(ProtectionType::AllowOnlyReading, "permission-psd");

    //Save the document to another Word file
    document->SaveToFile("Output/RestrictEditing.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Protect Sections of a Word Document in C++

Word allows you to lock some sections of your Word document and leave the rest available for editing. The following are the steps to protect selected sections of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyFormFields using Document->Protect() method.
  • Unprotect a particular section by passing false as an argument to the Section->SetProtectForm() method. Other sections will continue to be protected.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/ProtectionType.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample.docx");

    //Set the protection type as "AllowOnlyFormFields"
    document->Protect(ProtectionType::AllowOnlyFormFields, "permission-psd");

    //Unprotect section 2
    document->GetSections()->GetItem(1)->SetProtectForm(false);

    //Save the document to another Word file
    document->SaveToFile("Output/ProtectSections.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Create Editable Regions in a Word Document in C++

Aside from making certain sections editable, you can create editable regions based on text ranges in order to narrow down the scope of changes that users are able to make. The following are the steps to create editable regions in a read-only Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyReading using Document->Protect() method.
  • Create a PermissionStart object and a PermissionEnd object.
  • Insert the PermissionStart object at the beginning of a paragraph using DocumentObjectCollection->Insert(int index, Spire::Doc::lDocumentObject *entity) method, which indicates the start of an editable region.
  • Add the PermissionEnd object at the end of a paragraph using DocumentObjectCollection->Add(Spire::Doc::lDocumentObject *entity) method, which indicates the end of an editable region.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/PermissionEnd.h"
#include "Spire/Doc/PermissionStart.h"
#include "Spire/Doc/ProtectionType.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample2.docx");

    //Set the protect type to AllowOnlyReading
    document->Protect(ProtectionType::AllowOnlyReading, "permission-psd");

    //Create tags for permission start and end
    intrusive_ptr<PermissionStart> start = new PermissionStart(document, "regionOne");
    intrusive_ptr<PermissionEnd> end = new PermissionEnd(document, "regionOne");

    //Add the start and end tags to allow the selected paragraphs to be editable
    document->GetSections()->GetItem(0)->GetParagraphs()->GetItem(0)->GetChildObjects()->Insert(0, start);
    document->GetSections()->GetItem(0)->GetParagraphs()->GetItem(1)->GetChildObjects()->Add(end);

    //Save the document to another Word file
    document->SaveToFile("Output/SetEditableRegions.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Remove Editable Regions from a Word Document in C++

In order to remove the editable regions, you need to find the "PermissionStart" and "PermissionEnd" tags in the document and remove them. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editable regions using Document->LoadFromFile() method.
  • Traverse through all the child objects in the document, and determine if a certain child object is an instance of PermissionStart class or PermissionEnd class. If yes, remove the child object from the paragraph using Paragraph->GetChildObjects()->Remove(Spire::Doc::IDocumentObject *entity) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/PermissionEnd.h"
#include "Spire/Doc/PermissionStart.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;

int main() {

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

 //Load a Word file
 document->LoadFromFile("SetEditableRegions.docx");

 //Find "PermissionStart" and "PermissionEnd" tags and remove them
 for (int i = 0; i < document->GetSections()->GetCount(); i++)
 {
  intrusive_ptr<Section> section = document->GetSections()->GetItem(i);
  for (int j = 0; j < section->GetBody()->GetParagraphs()->GetCount(); j++)
  {
   intrusive_ptr<Paragraph> para = section->GetBody()->GetParagraphs()->GetItem(j);
   for (int k = 0; k < para->GetChildObjects()->GetCount(); k++)
   {
    intrusive_ptr<DocumentObject> obj = para->GetChildObjects()->GetItem(k);
    if (Object::Dynamic_cast<PermissionStart>(obj) != nullptr || Object::Dynamic_cast<PermissionEnd>(obj) != nullptr)
    {
     para->GetChildObjects()->Remove(obj);
    }
    else
    {
     k++;
    }
   }
  }
 }

 //Save the document to another Word file
 document->SaveToFile("Output/RemoveEditableRegions.docx", FileFormat::Docx2013);
 document->Close();
}

Remove Restrictions from a Word Document in C++

Spire.Doc for C++ allows you to remove editing restrictions without knowing the permission password. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editing restrictions using Document->LoadFromFile() method.
  • Set the protection type to NoProtection using Document->Protect() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/ProtectionType.h"
using namespace std;
using namespace Spire::Doc;

int main() {

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

    //Load a Word file
    document->LoadFromFile("RestrictEditing.docx");

    //Set the protect type to NoProtection
    document->Protect(ProtectionType::NoProtection);

    //Save the document to another Word file
    document->SaveToFile("Output/RemoveRestrictions.docx", FileFormat::Docx2013);
    document->Close();
}

Remove Password from a Password-Protected Word Document in C++

The password of an encrypted Word document can be removed if it is no longer needed. The following are the detailed steps.

  • Create a Document object.
  • Load a password-protected Word document using Document->LoadFromFile((LPCWSTR_S fileName, Spire::Doc::FileFormat fileFormat, LPCWSTR_S password) method.
  • Remove the password using Document->RemoveEncryption() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

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

    //Load an encrypted Word file
    document->LoadFromFile("Encryption.docx", FileFormat::Docx, "open-psd");

    //Remove the open password
    document->RemoveEncryption();

    //Save the document to another Word file
    document->SaveToFile("Output/RemovePassword.docx", FileFormat::Docx2013);
    document->Close();
}

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.

In Word, a watermark is a semi-transparent text or image that you can place in the background. Typically, watermarks are used to emphasize something important about a document. For example, you can use it to remind the user that the content is confidential or a draft. Or other times, you may want to add a washout mark to include the company logo in the document. In this article, you will learn how to insert text or image watermarks to Word documents in C++ 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

Insert a Text Watermark to Word in C++

Spire.Doc for C++ offers the TextWatermark class to represent a text watermark. The content and appearance of the watermark can be set using the methods under it. Once a text watermark is created, you can apply it to the whole document by using Document->SetWatermark() method. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Create a TextWatermark object.
  • Se the content and appearance of the watermark using the methods under the TextWatermark object.
  • Apply the text watermark to the document using Document->SetWatermrak() method.
  • Save the document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/WatermarkLayout.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/TextWatermark.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample.docx");

    //Create a TextWatermark object
    intrusive_ptr<TextWatermark> txtWatermark = new TextWatermark();

    //Set the content and format of the text watermark
    txtWatermark->SetText("CONFIDENTIAL");
    txtWatermark->SetFontSize(40);
    txtWatermark->SetSemitransparent(90);
    txtWatermark->SetFontName("Arial Black");
    txtWatermark->SetColor(Color::GetBlue());
    txtWatermark->SetLayout(WatermarkLayout::Diagonal);

    //Apply the text watermark to the document
    document->SetWatermark(txtWatermark);

    //Save the document
    document->SaveToFile("Output/TextWatermark.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Insert Text or Image Watermarks to Word

Insert an Image Watermark to Word in C++

Likewise, an image watermark can be created using PictureWatermark class. Once created, you can apply it to a Word document using Document->SetWatermark() method. Here are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Create a PictureWatermark object.
  • Set the image and appearance of the watermark using the methods under the PictureWatermark object.
  • Apply the image watermark to the document using Document->SetWatermrak() method.
  • Save the document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/PictureWatermark.h"
using namespace std;
using namespace Spire::Doc;

int main() {

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

    //Load a Word file
    document->LoadFromFile("sample.docx");

    //Create a PictureWatermark object
    intrusive_ptr<PictureWatermark> pictureWatermark = new PictureWatermark();

    //Specify image for the watermark
    pictureWatermark->SetPicture("company-png.png");
    pictureWatermark->SetScaling(100);
    pictureWatermark->SetIsWashout(false);

    //Apply the image watermark to the document
    document->SetWatermark(pictureWatermark);

    //Save the document 
    document->SaveToFile("Output/ImageWatermark.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Insert Text or Image Watermarks to 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.

Tuesday, 28 March 2023 01:06

C++: Remove Paragraphs in Word

While editing a Word document, there are numerous reasons to delete certain paragraphs in it. For example, it could be as simple as restructuring the document, or removing incorrect or irrelevant information to ensure document accuracy. In this article, you will learn how to programmatically remove paragraphs in a 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

Remove All Paragraphs in a Word Document in C++

To remove all paragraphs, you need to loop through all sections in a document and then delete all paragraphs in each section using Section->GetParagraphs()->Clear() method. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Traverse through each section of the document and then remove all paragraphs in the section using Section->GetParagraphs()->Clear() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;

int main() {
 //Specify the input and output file paths
 std::string inputFile = "sample.docx";
 std::string outputFile = "Output/RemoveAllParagraphs.docx";

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

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

 //Remove paragraphs from every section in the document
 for (int i = 0; i < document->GetSections()->GetCount(); i++)
 {
  intrusive_ptr<Section> section = document->GetSections()->GetItem(i);
  section->GetParagraphs()->Clear();
 }

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

C++: Remove Paragraphs in Word

Remove a Specific Paragraph in a Word Document in C++

If you find a paragraph that contains duplicate or useless information, Spire.Doc for C++ allows you to delete the specified paragraph using Section->GetParagraphs()->RemoveAt() method. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Get a specified section of the document using Document->GetSections()->GetItem() method.
  • Remove a specified paragraph in the section using Section->GetParagraphs()->RemoveAt() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;

int main() {
 //Specify the input and output file paths
 std::string inputFile = "sample.docx";
 std::string outputFile = "Output/RemoveSpecificParagraph.docx";

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

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

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

 //Remove the third paragraph in the section
 sec->GetParagraphs()->RemoveAt(2);

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

C++: Remove Paragraphs in Word

Remove Blank Paragraphs in a Word Document in C++

When there are many empty paragraphs/lines in a document, it quite necessary to remove them to improve readability. The following are the steps to remove all blank paragraphs/lines in a Word document.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Traverse through all paragraphs in the document and determine whether the paragraph is a blank paragraph.
  • Remove blank paragraphs from the document using section->GetBody()->GetChildObjects()->Remove() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/DocumentObjectType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;

int main() {
 //Specify the input and output file paths
 std::string inputFile = "Test.docx";
 std::string outputFile = "Output/RemoveEmptyLines.docx";

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

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

 //Traverse each paragraph in the Word document
 for (int i = 0; i < document->GetSections()->GetCount(); i++)
 {
  intrusive_ptr<Section> section = document->GetSections()->GetItem(i);

  for (int j = 0; j < section->GetBody()->GetChildObjects()->GetCount(); j++)
  {
   intrusive_ptr<DocumentObject> secChildObject = section->GetBody()->GetChildObjects()->GetItem(j);
   if (secChildObject->GetDocumentObjectType() == DocumentObjectType::Paragraph)
   {
    intrusive_ptr<Paragraph> para = Object::Dynamic_cast<Paragraph>(secChildObject);
    std::string paraText = para->GetText();

    //Determine if the paragraph is a blank paragraph
    if (paraText.empty())
    {
     //Remove blank paragraphs
     section->GetBody()->GetChildObjects()->Remove(secChildObject);
     j--;
    }
   }

  }
 }

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

C++: Remove Paragraphs 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.

Monday, 27 March 2023 01:27

C++: Create a Fillable Form in Word

Word allows you to create forms that other people can use to input information. Fillable forms are particularly useful when you need to gather data or feedback from many individuals and want to make sure that the formatting is consistent. The tools that you may need for creating a form include:

  • Content Controls: The areas where users input information in a form.
  • Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
  • Protection: Allows users to populate fields but not to make changes to the rest of the document.

Content controls in Word are containers for content that let users build structured documents. A structured document controls where content appears within the document. There are basically ten types of content controls available in Word 2013. This article focuses on how to create a fillable form in Word consisting of the following seven common content controls using Spire.Doc for C++.

Content Control Description
Plain Text A text field limited to plain text, so no formatting can be included.
Rich Text A text field that can contain formatted text or other items, such as tables, pictures, or other content controls.
Picture Accepts a single picture.
Drop-Down List A drop-down list displays a predefined list of items for the user to choose from.
Combo Box A combo box enables users to select a predefined value in a list or type their own value in the text box of the control.
Check Box A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked).
Date Picker Contains a calendar control from which the user can select a date.

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

Create a Fillable Form in Word in C++

The StructureDocumentTagInline class provided by Spire.Doc for C++ is used to create structured document tags for inline-level structures (DrawingML object, fields, etc.) in a paragraph. The SDTProperties property and the SDTContent property under this class shall be used to specify the properties and content of the current structured document tag. The following are the detailed steps to create a fillable form with content controls in Word.

  • Create a Document object.
  • Add a section using Document->AddSection() method.
  • Add a table using Section->AddTable() method.
  • Add a paragraph to a specific table cell using TableCell->AddParagraph() method.
  • Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph->GetChildObjects()->Add() method.
  • Specify the properties and content of the structured document tag using the methods under the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object. The type of the structured document tag is set through SDTProperties->SetSDTType() method.
  • Prevent users from editing content outside form fields using Document->Protect() method.
  • Save the document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/CalendarType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/SDTInlineContent.h"
#include "Spire/Doc/Documents/SDTProperties.h"
#include "Spire/Doc/Documents/SdtCheckBox.h"
#include "Spire/Doc/Documents/SdtComboBox.h"
#include "Spire/Doc/Documents/SdtDate.h"
#include "Spire/Doc/Documents/SdtDropDownList.h"
#include "Spire/Doc/Documents/SdtListItem.h"
#include "Spire/Doc/Documents/SdtListItemCollection.h"
#include "Spire/Doc/Documents/SdtPicture.h"
#include "Spire/Doc/Documents/SdtText.h"
#include "Spire/Doc/Documents/SdtType.h"
#include "Spire/Doc/Documents/StructureDocumentTagInline.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/ProtectionType.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/common/h/DateTime.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main() {

    //Create a Document object
    intrusive_ptr<Document> doc = new Document();

    //Add a section
    intrusive_ptr<Section> section = doc->AddSection();

    //add a table
    intrusive_ptr<Table> table = section->AddTable(true);
    table->ResetCells(7, 2);

    //Add text to the cells of the first column
    intrusive_ptr<Paragraph> paragraph = table->GetRows()->GetItem(0)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Plain Text Content Control");
    paragraph = table->GetRows()->GetItem(1)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Rich Text Content Control");
    paragraph = table->GetRows()->GetItem(2)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Picture Content Control");
    paragraph = table->GetRows()->GetItem(3)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Drop-Down List Content Control");
    paragraph = table->GetRows()->GetItem(4)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Check Box Content Control");
    paragraph = table->GetRows()->GetItem(5)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Combo box Content Control");
    paragraph = table->GetRows()->GetItem(6)->GetCells()->GetItem(0)->AddParagraph();
    paragraph->AppendText("Date Picker Content Control");

    //Add a plain text content control to the cell (0,1)
    paragraph = table->GetRows()->GetItem(0)->GetCells()->GetItem(1)->AddParagraph();
    intrusive_ptr<StructureDocumentTagInline> sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::Text);
    sdt->GetSDTProperties()->SetAlias("Plain Text");
    sdt->GetSDTProperties()->SetTag("Plain Text");
    sdt->GetSDTProperties()->SetIsShowingPlaceHolder(true);
    intrusive_ptr<SdtText> text = new SdtText(true);
    text->SetIsMultiline(false);
    sdt->GetSDTProperties()->SetControlProperties(text);
    intrusive_ptr<TextRange> tr = new TextRange(doc);
    tr->SetText("Click or tap here to enter text.");
    sdt->GetSDTContent()->GetChildObjects()->Add(tr);

    //Add a rich text content control to the cell (1,1)
    paragraph = table->GetRows()->GetItem(1)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::RichText);
    sdt->GetSDTProperties()->SetAlias("Rich Text");
    sdt->GetSDTProperties()->SetTag("Rich Text");
    sdt->GetSDTProperties()->SetIsShowingPlaceHolder(true);
    text = new SdtText(true);
    text->SetIsMultiline(false);
    sdt->GetSDTProperties()->SetControlProperties(text);
    tr = new TextRange(doc);
    tr->SetText("Click or tap here to enter text.");
    sdt->GetSDTContent()->GetChildObjects()->Add(tr);

    //Add a picture content control to the cell (2,1)
    paragraph = table->GetRows()->GetItem(2)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::Picture);
    sdt->GetSDTProperties()->SetAlias("Picture");
    sdt->GetSDTProperties()->SetTag("Picture");
    intrusive_ptr<SdtPicture> sdtPicture = new SdtPicture();
    sdt->GetSDTProperties()->SetControlProperties(sdtPicture);
    intrusive_ptr<DocPicture> pic = new DocPicture(doc);
    pic->LoadImage("1.png");
    sdt->GetSDTContent()->GetChildObjects()->Add(pic);

    //Add a dropdown list content control to the cell(3,1)
    paragraph = table->GetRows()->GetItem(3)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    sdt->GetSDTProperties()->SetSDTType(SdtType::DropDownList);
    sdt->GetSDTProperties()->SetAlias("Dropdown List");
    sdt->GetSDTProperties()->SetTag("Dropdown List");
    paragraph->GetChildObjects()->Add(sdt);
    intrusive_ptr<SdtDropDownList> sddl = new SdtDropDownList();
    sddl->GetListItems()->Add(new SdtListItem("Choose an item.", "1"));
    sddl->GetListItems()->Add(new SdtListItem("Item 2", "2"));
    sddl->GetListItems()->Add(new SdtListItem("Item 3", "3"));
    sddl->GetListItems()->Add(new SdtListItem("Item 4", "4"));
    sdt->GetSDTProperties()->SetControlProperties(sddl);
    tr = new TextRange(doc);
    tr->SetText(sddl->GetListItems()->GetItem(0)->GetDisplayText());
    sdt->GetSDTContent()->GetChildObjects()->Add(tr);

    //Add two check box content controls to the cell (4,1)
    paragraph = table->GetRows()->GetItem(4)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::CheckBox);
    intrusive_ptr<SdtCheckBox> scb = new SdtCheckBox();
    sdt->GetSDTProperties()->SetControlProperties(scb);
    tr = new TextRange(doc);
    sdt->GetChildObjects()->Add(tr);
    scb->SetChecked(false);
    paragraph->AppendText(" Option 1");

    paragraph = table->GetRows()->GetItem(4)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::CheckBox);
    scb = new SdtCheckBox();
    sdt->GetSDTProperties()->SetControlProperties(scb);
    tr = new TextRange(doc);
    sdt->GetChildObjects()->Add(tr);
    scb->SetChecked(false);
    paragraph->AppendText(" Option 2");

    //Add a combo box content control to the cell (5,1)
    paragraph = table->GetRows()->GetItem(5)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::ComboBox);
    sdt->GetSDTProperties()->SetAlias("Combo Box");
    sdt->GetSDTProperties()->SetTag("Combo Box");
    intrusive_ptr<SdtComboBox> cb = new SdtComboBox();
    cb->GetListItems()->Add(new SdtListItem("Choose an item."));
    cb->GetListItems()->Add(new SdtListItem("Item 2"));
    cb->GetListItems()->Add(new SdtListItem("Item 3"));
    sdt->GetSDTProperties()->SetControlProperties(cb);
    tr = new TextRange(doc);
    tr->SetText(cb->GetListItems()->GetItem(0)->GetDisplayText());
    sdt->GetSDTContent()->GetChildObjects()->Add(tr);

    //Add a date picker content control to the cell (6,1)
    paragraph = table->GetRows()->GetItem(6)->GetCells()->GetItem(1)->AddParagraph();
    sdt = new StructureDocumentTagInline(doc);
    paragraph->GetChildObjects()->Add(sdt);
    sdt->GetSDTProperties()->SetSDTType(SdtType::DatePicker);
    sdt->GetSDTProperties()->SetAlias("Date Picker");
    sdt->GetSDTProperties()->SetTag("Date Picker");
    intrusive_ptr<SdtDate> date = new SdtDate();
    date->SetCalendarType(CalendarType::Default);
    date->SetDateFormat("yyyy.MM.dd");
    date->SetFullDate(DateTime::GetNow());
    sdt->GetSDTProperties()->SetControlProperties(date);
    tr = new TextRange(doc);
    tr->SetText("Click or tap to enter a date.");
    sdt->GetSDTContent()->GetChildObjects()->Add(tr);

    //Allow users to edit the form fields only
    doc->Protect(ProtectionType::AllowOnlyFormFields, "permission-psd");

    //Save to file
    doc->SaveToFile("Output/WordForm.docx", FileFormat::Docx2013);
    doc->Close();
}

C++: Create a Fillable Form 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.

Friday, 24 March 2023 01:08

C++: Insert Images into Word Documents

Images can add visual variety to documents and convey information that is hard to express through text alone, such as complex concepts or emotions. They are a powerful tool to make your document easier to understand, more engaging, and more memorable. Whether you are designing a report or creating a marketing document, inserting images can enhance your communication with your readers and leave a lasting impression on them. In this article, you will learn how to insert images into Word documents in C++ 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

Insert an Image in a Word Document in C++

Spire.Doc for C++ offers the Paragraph->AppendPicture() method to insert an image into a Word document. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Add a section using Document->AddSection() method.
  • Add two paragraphs to the section using Section->AddParagraph() method.
  • Add text to the paragraphs using Paragraph->AppendText() method and set formatting.
  • Load an image using Image::FromFile() method.
  • Add the image to the first paragraph using Paragraph->AppendPicture() method.
  • Set width and height for the image using DocPicture->SetWidth() and DocPicture->SetHeight() methods.
  • Set a text wrapping style for the image using DocPicture->SetTextWrappingStyle() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextWrappingStyle.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> document = new Document();

 //Add a section
 intrusive_ptr<Section> section = document->AddSection();

 //Add the first paragraph
 intrusive_ptr<Paragraph> paragraph1 = section->AddParagraph();
 //Add text to the paragraph and set formatting
 intrusive_ptr <TextRange> tr = paragraph1->AppendText("Spire.Doc for C++ is a professional Word library specifically designed for developers to create, read, write, convert, merge, split, and compare Word documents in C++ applications with fast and high-quality performance.");
 tr->GetCharacterFormat()->SetFontName("Calibri");
 tr->GetCharacterFormat()->SetFontSize(11.0f);
 paragraph1->GetFormat()->SetLineSpacing(20.0f);
 paragraph1->GetFormat()->SetAfterSpacing(10.0f);

 //Add the second paragraph
 intrusive_ptr<Paragraph> paragraph2 = section->AddParagraph();
 //Add text to the paragraph and set formatting
 tr = paragraph2->AppendText("Almost all Word document elements are supported by Spire.Doc for C++, including pages, sections, headers, footers, digital signatures, footnotes, paragraphs, lists, tables, text, fields, hyperlinks, bookmarks, comments, images, style, background settings, document settings and protection. Furthermore, drawing objects including shapes, textboxes, images, OLE objects, Latex Math Symbols, MathML Code and controls are supported as well.");
 tr->GetCharacterFormat()->SetFontName("Calibri");
 tr->GetCharacterFormat()->SetFontSize(11.0f);
 paragraph2->GetFormat()->SetLineSpacing(20.0f);

 //Add the image to the first paragraph
 intrusive_ptr<DocPicture> picture = paragraph1->AppendPicture("Spire.Doc.png");
 //Set image width and height
 picture->SetWidth(100);
 picture->SetHeight(100);
 //Set text wrapping style for the image
 picture->SetTextWrappingStyle(TextWrappingStyle::Tight);

 //Save the result document
 document->SaveToFile("InsertImage.docx", FileFormat::Docx2013);
 document->Close();
}

C++: Insert Images into Word Documents

Insert an Image at a Specified Location in a Word document in C++

Spire.Doc for C++ enables you to insert an image into a Word document and set its position by using the DocPicture->SetHorizontalPosition() and DocPicture->SetVerticalPosition() methods. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Add a section using Document->AddSection() method.
  • Add a paragraph to the section using Section->AddParagraph() method.
  • Add text to the paragraph using Paragraph->AppendText() method and set formatting.
  • Load an image using Image::FromFile() method.
  • Add the image to the paragraph using Paragraph->AppendPicture() method.
  • Set width and height for the image using DocPicture->SetWidth() and DocPicture->SetHeight() methods.
  • Set the horizontal position and vertical position for the image using DocPicture->SetHorizontalPosition() and DocPicture->SetVerticalPosition() methods.
  • Set a text wrapping style for the image using DocPicture->SetTextWrappingStyle() method (note that the position settings are not applicable when the text wrapping style is Inline).
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BuiltinStyle.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextWrappingStyle.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> document = new Document();

 //Add a section
 intrusive_ptr<Section> section = document->AddSection();

 //Add a paragraph to the section
 intrusive_ptr<Paragraph> paragraph = section->AddParagraph();

 //Add text to the paragraph and set formatting
 intrusive_ptr<TextRange> tr = paragraph->AppendText("The sample demonstrates how to insert an image at a specified location in a Word document.");
 tr->GetCharacterFormat()->SetFontName("Calibri");
 paragraph->ApplyStyle(BuiltinStyle::Heading2);

 //Add the image to the paragraph
 intrusive_ptr<DocPicture> picture = paragraph->AppendPicture("Spire.Doc.png");

 //Set image size
 picture->SetWidth(100);
 picture->SetHeight(100);

 //Set image position
 picture->SetHorizontalPosition(180.0F);
 picture->SetVerticalPosition(60.0F);

 //Set a text wrapping style for the image (note that the position settings are not applicable when the text wrapping style is Inline)
 picture->SetTextWrappingStyle(TextWrappingStyle::Through);

 //Save the result document
 document->SaveToFile("InsertImageAtSpecifiedLocation.docx", FileFormat::Docx);
 document->Close();
}

C++: Insert Images into Word Documents

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.

The find and replace feature in Microsoft Word is an essential tool when editing documents. It enables you to quickly find a specific word or phrase in a Word document and lets you replace all instances of it at once. This is especially helpful in situations where you need to update information or correct misspelled words in large Word documents. In this article, you will learn how to find and replace text in Word documents in C++ 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

Find Text and Replace All Its Instances with New Text

You can find a text and replace all its instances with another text easily using the Document->Replace() method. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Find a specific text and replace all its instances with another text using Document->Replace() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> document = new Document();

 //Load a Word document
 document->LoadFromFile("Input.docx");

 //Find a specific text and replace all its instances with another text
 document->Replace("Spire.Doc", "Eiceblue", false, true);

 //Save the result document
 document->SaveToFile("ReplaceAllInstances.docx", FileFormat::Docx2013);
 document->Close();
}

C++: Find and Replace Text in Word Documents

Find Text and Replace Its First Instance with New Text

Spire.Doc for C++ provides the Document->SetReplaceFirst() method which enables you to change the replacement mode from replacing all instances to replacing the first instance. The following steps explain how to find a text and replace its first instance:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Change the replacement mode to replace the first instance using Document->SetReplaceFirst(true) method.
  • Replace the first instance of a text with another text using Document->Replace() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> document = new Document();

 //Load a Word document
 document->LoadFromFile("Input.docx");

 //Change the replacement mode to replace the first match
 document->SetReplaceFirst(true);

 //Replace the first instance of a text with another text
 document->Replace("Spire.Doc", "Eiceblue", false, true);

 //Save the result document
 document->SaveToFile("ReplaceFirstInstance.docx", FileFormat::Docx2013);
 document->Close();
}

C++: Find and Replace Text in Word Documents

Find and Replace Text Using a Regular Expression

You can replace a text matching a regular expression with new text using the Document->Replace() method and passing a Regex instance and the new text to the method as parameters. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Initialize an instance of the Regex class to create a regular expression.
  • Find the text matching the regex and replace it with another text using Document->Replace() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <regex>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Regex.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> doc = new Document();
 //Load a Word document
 doc->LoadFromFile("Input1.docx");

 //Create a regex to match the text that starts with #
 intrusive_ptr<Regex> regex = new Regex("\\#\\w+\\b");

 //Find the text matching the regex and replace it with another text
 doc->Replace(regex, "Monitor");

 //Save the result document
 doc->SaveToFile("ReplaceWithRegex.docx", FileFormat::Docx2013);
 doc->Close();;
}

C++: Find and Replace Text in Word Documents

Find and Replace Text with an Image

Spire.Doc for C++ doesn't offer a direct method to replace text with image, but you can achieve this by inserting the image at the position of the text and then removing the text from the document. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Find a specific text using Document->FindAllString() method and put the found text into a vector.
  • Iterate through the found text in the vector.
  • Initialize an instance of DocPicture class and load an image using DocPicture->LoadImageSpire() method.
  • Get the found text as a single text range and then get the index of the text range in its owner paragraph.
  • Insert an image at the position of the text range and then remove the text range from the document.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main()
{
 //Initialize an instance of the Document class
 intrusive_ptr<Document> doc = new Document();

 //Load a Word document
 doc->LoadFromFile("Input.docx");

 //Find a text in the document and put the found results into a vector
 vector<intrusive_ptr<TextSelection>> selections = doc->FindAllString("Spire.Doc", true, true);

 int index = 0;
 intrusive_ptr<TextRange> range = nullptr;

 //Iterate through the found text in the vector
 for (auto selection : selections)
 {
  //Load an image
  intrusive_ptr<DocPicture> pic = new DocPicture(doc);
  pic->LoadImage("img.jpg");
  //Get the found text as a single text range
  range = selection->GetAsOneRange();
  //Get the index of the text range in its owner paragraph
  index = range->GetOwnerParagraph()->GetChildObjects()->IndexOf(range);
  //Insert an image at the index
  range->GetOwnerParagraph()->GetChildObjects()->Insert(index, pic);
  //Remove the text range
  range->GetOwnerParagraph()->GetChildObjects()->Remove(range);
 }

 //Save the result document
 doc->SaveToFile("ReplaceWithImage.docx", FileFormat::Docx2013);
 doc->Close();
}

C++: Find and Replace Text in Word Documents

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.

Wednesday, 08 March 2023 01:26

C++: Create Tables in Word Documents

A table is a powerful tool for organizing and presenting data. It arranges data into rows and columns, making it easier for authors to illustrate the relationships between different data categories and for readers to understand and analyze complex data. In this article, you will learn how to programmatically create tables in Word documents in C++ 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

Create a Table in Word in C++

Spire.Doc for C++ offers the Section->AddTable() method to add a table to a section of a Word document. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Add a section to the document using Document->AddSection() method.
  • Define the data for the header row and remaining rows, storing them in a one-dimensional vector and a two-dimensional vector respectively.
  • Add a table to the section using Section->AddTable() method.
  • Specify the number of rows and columns in the table using Table->ResetCells(int, int) method.
  • Add data in the one-dimensional vector to the header row and set formatting.
  • Add data in the two-dimensional vector to the remaining rows and set formatting.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire.Doc.C.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Documents/MarginsF.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TableRowHeightType.h"
#include "Spire/Doc/Documents/VerticalAlignment.h"
#include "Spire/Doc/Fields/Shapes/Shading.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CellFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/PageSetup.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
using namespace Spire::Doc::Fields::Shapes;

int main()
{
	//Initialize an instance of the Document class
	intrusive_ptr<Document> doc = new Document();

	//Add a section to the document
	intrusive_ptr<Section> section = doc->AddSection();

	//Set page margins for the section
	section->GetPageSetup()->GetMargins()->SetAll(72);

	//Define the data for the header row
	vector<string> header = { "Name", "Capital", "Continent", "Area", "Population" };
	//Define the data for the remaining rows
	vector<vector<string>> data =
	{
		{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
		{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
		{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
		{"Canada", "Ottawa", "North America", "9976147", "26500000"},
		{"Chile", "Santiago", "South America", "756943", "13200000"},
		{"Colombia", "Bogota", "South America", "1138907", "33000000"},
		{"Cuba", "Havana", "North America", "114524", "10600000"},
		{"Ecuador", "Quito", "South America", "455502", "10600000"},
		{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
		{"Guyana", "Georgetown", "South America", "214969", "800000"},
		{"Jamaica", "Kingston", "North America", "11424", "2500000"},
		{"Mexico", "Mexico City", "North America", "1967180", "88600000"},
		{"Nicaragua", "Managua", "North America", "139000", "3900000"},
		{"Paraguay", "Asuncion", "South America", "406576", "4660000"},
		{"Peru", "Lima", "South America", "1285215", "21600000"},
		{"United States", "Washington", "North America", "9363130", "249200000"},
		{"Uruguay", "Montevideo", "South America", "176140", "3002000"},
		{"Venezuela", "Caracas", "South America", "912047", "19700000"}
	};

	//Add a table to the section
	intrusive_ptr<Table> table = section->AddTable(true);
	//Specify the number of rows and columns for the table
	table->ResetCells(data.size() + 1, header.size());

	//Set the first row as the header row
	intrusive_ptr<TableRow> row = table->GetRows()->GetItem(0);
	row->SetIsHeader(true);

	//Set height and background color for the header row
	row->SetHeight(20);
	row->SetHeightType(TableRowHeightType::Exactly);
	for (int i = 0; i < row->GetCells()->GetCount(); i++)
	{
		row->GetCells()->GetItem(i)->GetCellFormat()->GetShading()->SetBackgroundPatternColor(Color::FromArgbRGB(142, 170, 219));
	}

	//Add data to the header row and set formatting
	for (size_t i = 0; i < header.size(); i++)
	{
		//Add a paragraph
		intrusive_ptr<Paragraph> p1 = row->GetCells()->GetItem(i)->AddParagraph();
		//Set alignment
		p1->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
		row->GetCells()->GetItem(i)->GetCellFormat()->SetVerticalAlignment(VerticalAlignment::Middle);
		//Add data
		intrusive_ptr<TextRange> tR1 = p1->AppendText(header[i].c_str());
		//Set data formatting
		tR1->GetCharacterFormat()->SetFontName("Calibri");
		tR1->GetCharacterFormat()->SetFontSize(12);
		tR1->GetCharacterFormat()->SetBold(true);
	}

	//Add data to the remaining rows and set formatting
	for (size_t r = 0; r < data.size(); r++)
	{
		//Set height for the remaining rows
		intrusive_ptr<TableRow> dataRow = table->GetRows()->GetItem(r + 1);
		dataRow->SetHeight(20);
		dataRow->SetHeightType(TableRowHeightType::Exactly);

		for (size_t c = 0; c < data[r].size(); c++)
		{
			//Add a paragraph
			intrusive_ptr<Paragraph> p2 = dataRow->GetCells()->GetItem(c)->AddParagraph();
			//Set alignment
			dataRow->GetCells()->GetItem(c)->GetCellFormat()->SetVerticalAlignment(VerticalAlignment::Middle);
			//Add data
			intrusive_ptr<TextRange> tR2 = p2->AppendText(data[r][c].c_str());
			//Set data formatting
			tR2->GetCharacterFormat()->SetFontName("Calibri");
			tR2->GetCharacterFormat()->SetFontSize(11);
		}
	}

	//Save the result document
	doc->SaveToFile("CreateTable.docx", FileFormat::Docx2013);
	doc->Close();
}

C++: Create Tables in Word Documents

Create a Nested Table in Word in C++

Spire.Doc for C++ offers the TableCell->AddTable() method to add a nested table to a specific table cell. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Add a section to the document using Document->AddSection() method.
  • Add a table to the section using Section.AddTable() method.
  • Specify the number of rows and columns in the table using Table->ResetCells(int, int) method.
  • Get the rows of the table and add data to the cells of each row.
  • Add a nested table to a specific table cell using TableCell->AddTable() method.
  • Specify the number of rows and columns in the nested table.
  • Get the rows of the nested table and add data to the cells of each row.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/AutoFitBehaviorType.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/MarginsF.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/PageSetup.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/TableRow.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main()
{
	//Initialize an instance of the Document class
	intrusive_ptr<Document> doc = new Document();
	//Add a section to the document
	intrusive_ptr<Section> section = doc->AddSection();

	//Set page margins for the section
	section->GetPageSetup()->GetMargins()->SetAll(72);

	//Add a table to the section
	intrusive_ptr<Table> table = section->AddTable(true);
	//Set the number of rows and columns in the table
	table->ResetCells(2, 2);

	//Autofit the table width to window
	table->AutoFit(AutoFitBehaviorType::AutoFitToWindow);

	//Get the table rows
	intrusive_ptr<TableRow> row1 = table->GetRows()->GetItem(0);
	intrusive_ptr<TableRow> row2 = table->GetRows()->GetItem(1);

	//Add data to cells of the table
	intrusive_ptr<TableCell> cell1 = row1->GetCells()->GetItem(0);
	intrusive_ptr<TextRange> tR = cell1->AddParagraph()->AppendText("Product");
	tR->GetCharacterFormat()->SetFontSize(13);
	tR->GetCharacterFormat()->SetBold(true);
	intrusive_ptr<TableCell> cell2 = row1->GetCells()->GetItem(1);
	tR = cell2->AddParagraph()->AppendText("Description");
	tR->GetCharacterFormat()->SetFontSize(13);
	tR->GetCharacterFormat()->SetBold(true);
	intrusive_ptr<TableCell> cell3 = row2->GetCells()->GetItem(0);
	cell3->AddParagraph()->AppendText("Spire.Doc for C++");
	intrusive_ptr<TableCell> cell4 = row2->GetCells()->GetItem(1);
	cell4->AddParagraph()->AppendText("Spire.Doc for C++ is a professional Word "
		"library specifically designed for developers to create, "
		"read, write and convert Word documents in C++ "
		"applications with fast and high-quality performance.");

	//Add a nested table to the fourth cell
	intrusive_ptr<Table> nestedTable = cell4->AddTable(true);
	//Set the number of rows and columns in the nested table
	nestedTable->ResetCells(3, 2);

	//Autofit the table width to content
	nestedTable->AutoFit(AutoFitBehaviorType::AutoFitToContents);

	//Get table rows
	intrusive_ptr<TableRow> nestedRow1 = nestedTable->GetRows()->GetItem(0);
	intrusive_ptr<TableRow> nestedRow2 = nestedTable->GetRows()->GetItem(1);
	intrusive_ptr<TableRow> nestedRow3 = nestedTable->GetRows()->GetItem(2);

	//Add data to cells of the nested table
	intrusive_ptr<TableCell> nestedCell1 = nestedRow1->GetCells()->GetItem(0);
	tR = nestedCell1->AddParagraph()->AppendText("Item");
	tR->GetCharacterFormat()->SetBold(true);
	intrusive_ptr<TableCell> nestedCell2 = nestedRow1->GetCells()->GetItem(1);
	tR = nestedCell2->AddParagraph()->AppendText("Price");
	tR->GetCharacterFormat()->SetBold(true);
	intrusive_ptr<TableCell> nestedCell3 = nestedRow2->GetCells()->GetItem(0);
	nestedCell3->AddParagraph()->AppendText("Developer Subscription");
	intrusive_ptr<TableCell> nestedCell4 = nestedRow2->GetCells()->GetItem(1);
	nestedCell4->AddParagraph()->AppendText("$999");
	intrusive_ptr<TableCell> nestedCell5 = nestedRow3->GetCells()->GetItem(0);
	nestedCell5->AddParagraph()->AppendText("Developer OEM Subscription");
	intrusive_ptr<TableCell> nestedCell6 = nestedRow3->GetCells()->GetItem(1);
	nestedCell6->AddParagraph()->AppendText("$2999");

	//Save the result document
	doc->SaveToFile("CreateNestedTable.docx", FileFormat::Docx2013);
	doc->Close();
}

C++: Create Tables in Word Documents

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.

A background color or picture can help make a document more aesthetically pleasing and attention-grabbing. If you are creating a document for marketing, education, or presentation purposes, adding an attractive background color or picture would be very useful. In this article, we will demonstrate how to programmatically add background color or picture to Word documents in C++ 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

Add a Background Color to Word in C++

Adding a background color to a Word document is very straightforward using Spire.Doc for C++. You just need to set the document’s background type as color and then specify a color as the background. The detailed steps are as follows.

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Get the document's background using Document->GetBackground() method.
  • Set the background type as color using Background->SetType(BackgroundType::Color) method.
  • Set the background color using Background->SetColor() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Background.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BackgroundType.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main()
{
	//Initialize an instance of the Document class
	intrusive_ptr<Document> document = new Document();
	//Load a Word document
	document->LoadFromFile("Sample.docx");

	//Get the document's background
	intrusive_ptr <Background> background = document->GetBackground();
	//Set the background type as color
	background->SetType(BackgroundType::Color);
	//Set the background color
	background->SetColor(Color::GetAliceBlue());

	//Save the result document
	document->SaveToFile("AddBackgroundColor.docx", FileFormat::Docx2013);
	document->Close();
}

C++: Add Background Color or Picture to Word Documents

Add a Gradient Background to Word in C++

To add a gradient background, you need to set the background type as gradient, specify the gradient color and then set the gradient shading variant and style. The detailed steps are as follows.

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Get the document's background using Document->GetBackground() method.
  • Set the background type as gradient using Background->SetType(BackgroundType::Gradient) method.
  • Specify two gradient colors using Background->GetGradient()->SetColor1() and Background->GetGradient()->SetColor2() methods.
  • Set gradient shading variant and style using Background->GetGradient()->SetShadingVariant() and Background->GetGradient()->SetShadingStyle() methods.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Background.h"
#include "Spire/Doc/BackgroundGradient.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BackgroundType.h"
#include "Spire/Doc/Documents/GradientShadingStyle.h"
#include "Spire/Doc/Documents/GradientShadingVariant.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main()
{
	//Initialize an instance of the Document class
	intrusive_ptr <Document> document = new Document();
	//Load a Word document
	document->LoadFromFile("Sample.docx");

	//Get the document's background
	intrusive_ptr <Background> background = document->GetBackground();
	//Set the background type as gradient
	background->SetType(BackgroundType::Gradient);

	//Specify two gradient colors 
	background->GetGradient()->SetColor1(Color::GetWhite());
	background->GetGradient()->SetColor2(Color::GetLightBlue());

	//Set gradient shading variant and style
	background->GetGradient()->SetShadingVariant(GradientShadingVariant::ShadingDown);
	background->GetGradient()->SetShadingStyle(GradientShadingStyle::Horizontal);

	//Save the result document
	document->SaveToFile("AddGradientBackground.docx", FileFormat::Docx2013);
	document->Close();
}

C++: Add Background Color or Picture to Word Documents

Add a Background Picture to Word in C++

To add a background image to a Word document, you need to set the background type as picture, and then insert a picture as the background. The detailed steps are as follows.

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile() method.
  • Get the document's background using Document->GetBackground() method.
  • Set the background type as picture using Background->SetType(BackgroundType::Picture) method.
  • Set the background picture using Background->SetPicture() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Background.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BackgroundType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main()
{
	//Initialize an instance of the Document class
	intrusive_ptr <Document> document = new Document();
	//Load a Word document
	document->LoadFromFile("Sample.docx");

	//Get the document's background
	intrusive_ptr <Background> background = document->GetBackground();
	//Set the background type as picture
	background->SetType(BackgroundType::Picture);

	//Set the background picture
	background->SetPicture("background.png");

	//Save the result document
	document->SaveToFile("AddBackgroundPicture.docx", FileFormat::Docx2013);
	document->Close();
}

C++: Add Background Color or Picture to Word Documents

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.

Monday, 27 February 2023 00:57

C++: Insert or Remove Page Breaks in Word

In MS Word, a Page Break is an important feature of page layout that helps you start a new page wherever you want. After inserting page breaks, all formatting of the previous page applies to the new page, which makes the whole document neat and well organized. In this article, you will learn how to programmatically add or remove page breaks in a 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

Insert a Page Break after a Specific Paragraph in Word in C++

Spire.Doc for C++ offers the Paragraph->AppendBreak(BreakType::PageBreak) method to insert a page break after a paragraph. Once inserted, a symbol indicating the page break will be shown. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Get a specified section using Document->GetSections()->GetItem(sectionIndex) method.
  • Get a specified paragraph using Section->GetParagraphs()->GetItem(paragraphIndex) method.
  • Add a page break to end of the paragraph using Paragraph->AppendBreak(BreakType::PageBreak) method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Break.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/CompositeDocumentObject.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/BreakType.h"
#include "Spire/Doc/Documents/DropDownItem.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/ShapeObject.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main() {
 //Specify input file path and name
 std::string input_path = "";
 std::string inputFile = input_path + "Input.docx";

 //Specify output file path and name
 std::string output_path = "Output/";
 std::string outputFile = output_path + "InsertPageBreak.docx";

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

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

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

 //Get the 2nd paragraph in the section
 intrusive_ptr <Paragraph> paragraph = section->GetParagraphs()->GetItem(1);

 //Insert a page break after the paragraph
 paragraph->AppendBreak(BreakType::PageBreak);

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

C++: Insert or Remove Page Breaks in Word

Insert a Page Break after a Specific Text in Word in C++

In addition to inserting a page break after a paragraph, Spire.Doc for C++ also allows you to find a specified text and then insert the page break after the specified text. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Find a specified text using Document->FindString() method.
  • Get the text range of the specified text using TextSelection->GetAsOneRange() method.
  • Get the paragraph where the text range is located using TextRange->GetOwnerParagraph() method.
  • Get the position index of the text range in the paragraph using Paragraph->GetChildObjects()->IndexOf() method.
  • Initialize an instance of Break class to create a page break.
  • Insert the page break after the specified text using Paragraph->GetChildObjects()->Insert() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Break.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BreakType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main() {
 //Specify input file path and name
 std::string input_path = "";
 std::string inputFile = input_path + "Input.docx";

 //Specify output file path and name
 std::string output_path = "Output/";
 std::string outputFile = output_path + "InsertPageBreakAfterText.docx";

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

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

 //Find a specified text
 intrusive_ptr<TextSelection> selection = document->FindString("infrastructure", true, true);

 //Get the text range of the specified text
 intrusive_ptr<TextRange> range = selection->GetAsOneRange();

 //Get the paragraph where the text range is located
 intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();

 //Get the position index of the text range in the paragraph
 int index = paragraph->GetChildObjects()->IndexOf(range);

 //Create a page break
 intrusive_ptr<Break> pageBreak = new Break(document, BreakType::PageBreak);

 //Insert a page break after the specified text
 paragraph->GetChildObjects()->Insert(index + 1, pageBreak);

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

C++: Insert or Remove Page Breaks in Word

Remove Page Breaks in a Word Document in C++

Some mistakenly added page breaks can mess up the structure of your entire document, so it's quite necessary to remove them. The following are the steps to remove page breaks in a Word document.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Traverse through each paragraph in the first section, and then traverse through each child object of a paragraph.
  • Determine whether the child object type is a page break. If yes, remove the page break from the paragraph using Paragraph->GetChildObjects()->Remove() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Break.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/BreakType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;

int main() {
 //Specify input file path and name
 std::string input_path = "";
 std::string inputFile = input_path + "InsertPageBreak.docx";

 //Specify output file path and name
 std::string output_path = "Output/";
 std::string outputFile = output_path + "RemovePageBreaks.docx";

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

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

 //Traverse through each paragraph in the first section of the document
 for (int j = 0; j < document->GetSections()->GetItem(0)->GetParagraphs()->GetCount(); j++)
 {
  intrusive_ptr<Paragraph> p = document->GetSections()->GetItem(0)->GetParagraphs()->GetItem(j);

  //Traverse through each child object of a paragraph
  for (int i = 0; i < p->GetChildObjects()->GetCount(); i++)
  {
   intrusive_ptr <DocumentObject> obj = p->GetChildObjects()->GetItem(i);

   //Determine whether the child object type is a page break
   if (Object::CheckType<Break>(obj) && (Object::Dynamic_cast<Break>(obj))->GetBreakType() == BreakType::PageBreak)
   {
    //Remove the page break from the paragraph
    p->GetChildObjects()->Remove(obj);
   }
  }
 }

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

C++: Insert or Remove Page Breaks 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.

Friday, 24 February 2023 00:57

C++: Convert Word to PDF

PDF is one of the most versatile, universal and feature-rich file formats in use today. Compared to Word, PDF documents are less likely to lose formatting when they’re opened on various devices. Additionally, PDF has absolute advantages over Word in terms of document security, archiving and transmission. These are some of the reasons why we should convert Word to PDF. In this article, you will learn how to convert Word to PDF and how to set conversion options in C++ 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

Convert Doc or Docx to PDF in C++

The Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method provided by Spire.Doc for C++ allows to save Word as PDF, XPS, HTML, RTF, etc. If you just want to save your Word documents as regular PDFs without additional settings, follow the steps below.

  • Create a Document object.
  • Load a sample Word file using Document->LoadFromFile() method.
  • Save the document to PDF using Doucment->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

 //Specify input file path
 string inputFilePath = "sample.docx";

 //Specify output file path and name
 string outputPath = "Output/";
 string outputFile = outputPath + "ToPDF.pdf";

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

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

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

C++: Convert Word to PDF

Convert Word to PDF with Bookmarks in C++

Bookmarks can enhance the readability of a document. When generating PDF from Word, you may would like to preserve existing bookmarks of the Word document or create bookmarks from the headings. The following are the steps to convert Word to PDF with bookmarks.

  • Create a Document object.
  • Load a sample Word file using Document->LoadFromFile() method.
  • Create a ToPdfParameterList object, which is used to set conversion options.
  • Create bookmarks in PDF from the headings in Word using ToPdfParameterList.SetCreateWordBookmarksUsingHeadings() method.
  • Save the document to PDF with bookmarks using Doucment->SaveToFile(LPCWSTR_S fileName, ToPdfParameterList* paramList) method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/ToPdfParameterList.h"
using namespace std;
using namespace Spire::Doc;

int main() {

 //Specify input file path
 string inputFilePath = "sample.docx";

 //Specify output file path and name
 string outputPath = "Output/";
 string outputFile = outputPath + "ToPDF.pdf";

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

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

 //Create a ToPdfParameterList object
 intrusive_ptr<ToPdfParameterList> parameters = new ToPdfParameterList();

 //Create bookmarks from Word headings
 parameters->SetCreateWordBookmarksUsingHeadings(true);

 //Create bookmarks in PDF from existing bookmarks in Word
 //parameters->SetCreateWordBookmarks(true);

 //Save the document to PDF
 document->SaveToFile(outputFile.c_str(), parameters);
 document->Close();
}

C++: Convert Word to PDF

Convert Word to PDF with Fonts Embedded in C++

By embedding fonts used in a Word document into the PDF document, you ensure that the PDF document looks the same on any device that does not have the appropriate fonts installed. The steps to embed fonts in PDF during conversion are as follows.

  • Create a Document object.
  • Load a sample Word file using Document->LoadFromFile() method.
  • Create a ToPdfParameterList object, which is used to set conversion options.
  • Embed fonts in generated PDF using ToPdfParameterList.SetIsEmbeddedAllFonts() method.
  • Save the document to PDF using Doucment->SaveToFile(LPCWSTR_S fileName, ToPdfParameterList* paramList) method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/ToPdfParameterList.h"
using namespace std;
using namespace Spire::Doc;

int main() {

 //Specify input file path
 string inputFilePath = "sample.docx";

 //Specify output file path and name
 string outputPath = "Output/";
 string outputFile = outputPath + "ToPDF.pdf";

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

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

 //Create a ToPdfParameterList object
 intrusive_ptr<ToPdfParameterList> parameters = new ToPdfParameterList();

 //Embed fonts used in Word in generated PDF
 parameters->SetIsEmbeddedAllFonts(true);

 //Save the document to PDF
 document->SaveToFile(outputFile.c_str(), parameters);
 document->Close();
}

C++: Convert Word to PDF

Set Image Quality When Converting Word to PDF in C++

A document containing a large number of high-quality images will often be large in size. When you convert Word to PDF, you can decide whether to compress the image quality or not. The following are the detailed steps.

  • Create a Document object.
  • Load a sample Word file using Document->LoadFromFile() method.
  • Set the image quality using Document->SetJPEGQuality() mehtod
  • Save the document to PDF using Doucment->SaveToFile() method.
  • C++
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

 //Specify input file path
 string inputFilePath = "sample.docx";

 //Specify output file path and name
 string outputPath = "Output/";
 string outputFile = outputPath + "ToPDF.pdf";

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

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

 //Compress image to 40% of the original quality
 document->SetJPEGQuality(40);

 //Preserve original image quality
 //document->SetJPEGQuality(100);

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

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.

Page 4 of 6