C++: Merge Word Documents

2023-06-09 01:25:58 Written by Koohji

Merging Word documents can be useful when you want to consolidate information from multiple files. For example, if you have a series of reports that relate to a specific project or topic, you may want to merge them into one document for easier access, distribution, and archiving purposes. In this article, we will demonstrate how to merge Word documents into one 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

Merge Word Documents by Inserting Files in C++

The Document->InsertTextFromFile(LPCWSTR_S fileName, FileFormat fileFormat) method provided by Spire.Doc for C++ enables developers to merge Word documents by inserting the contents of other Word documents into the original Word document. Using this method, the inserted contents will begin on a new page. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Insert another document into the loaded Word document using the Document->InsertTextFromFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
  • Save the result document to a specific location using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
  • C++
#include "Spire.Doc.o.h"

using namespace Spire::Doc;
using namespace std;

int main()
{
	//Specify the input file paths
	wstring inputFile_1 = L"Sample1.docx";
	wstring inputFile_2 = L"Sample2.docx";
	//Specify the output file path
	wstring outputFile = L"MergeWordDocumentsByInsertingFile.docx";

	//Initialize an instance of the Document class
	intrusive_ptr<Document> doc = new Document();
	//Load a Word document
	doc->LoadFromFile(inputFile_1.c_str());

	//Insert another document into the loaded document
	doc->InsertTextFromFile(inputFile_2.c_str(), FileFormat::Auto);

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

C++: Merge Word Documents

Merge Word Documents by Cloning Contents in C++

If you want to merge documents without starting from a new page, you can clone the contents of other documents and add them to the end of the original document. This approach can avoid creating unwanted section breaks. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Get the last section of the first Word document using the Document->GetLastSection() method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Iterate through all sections of the second Word document, and then iterate through all child objects of each section.
  • Clone each child object using the DocumentObject->Clone() method.
  • Add the cloned child object to the end of the last section of the first Word document using the Section->GetBody()->GetChildObjects()->Add(intrusive_ptr<IDocumentObject> entity) method.
  • Save the first Word document to a specific location using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
  • C++
#include "Spire.Doc.o.h"

using namespace Spire::Doc;
using namespace std;

int main()
{
	//Specify the input file paths
	wstring inputFile_1 = L"Sample1.docx";
	wstring inputFile_2 = L"Sample2.docx";
	//Specify the output file path
	wstring outputFile =  L"MergeWordDocumentsByCloningContents.docx";

	//Initialize an instance of the Document class
	intrusive_ptr<Document> document1 = new Document();
	//Load the first Word document
	document1->LoadFromFile(inputFile_1.c_str(), FileFormat::Auto);
	//Get the last section of the first Word document
	intrusive_ptr<Section> lastSection = document1->GetLastSection();

	//Initialize an instance of the Document class
	intrusive_ptr<Document> document2 = new Document();
	//Load the second Word document
	document2->LoadFromFile(inputFile_2.c_str(), FileFormat::Auto);

	//Get the number of sections of the second Word document
	int sectionCount = document2->GetSections()->GetCount();
	
	//Iterate through the sections of the second Word document
	for (int i = 0; i < sectionCount; i++)
	{
		intrusive_ptr<Section> section = document2->GetSections()->GetItemInSectionCollection(i);
		int sectionChildObjectsCount = section->GetBody()->GetChildObjects()->GetCount();
		//Iterate through the child objects in each section of the second Word document
		for (int j = 0; j < sectionChildObjectsCount; j++)
		{
			intrusive_ptr<DocumentObject> documentObject = section->GetBody()->GetChildObjects()->GetItem(j);
			//Clone each child object
			intrusive_ptr<DocumentObject> clonedObject = documentObject->Clone();
			//Add each cloned child object to the end of the last section of the first Word document
			lastSection->GetBody()->GetChildObjects()->Add(clonedObject);
		}
	}

	//Save the first Word document to a specific location
	document1->SaveToFile(outputFile.c_str(), FileFormat::Docx);
	document1->Close();
	document2->Close();
}

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

Java: Set the Font in Word

2024-12-05 01:08:00 Written by Koohji

When it comes to creating professional documents, choosing the right font is crucial. Using multiple fonts in one document can help distinguish different types of content such as headings, body text or annotations, ultimately enhancing the document's readability. Moreover, different fonts have unique emotional tones and styles. For instance, handwritten fonts often convey warmth and intimacy while serif fonts are ideal for traditional and formal contexts.

In this article, you will learn how to set the font in a Word document in Java using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.1.3</version>
    </dependency>
</dependencies>

Apply a Font to a Paragraph in Java

Typically, a consistent font style throughout a paragraph keeps the text looking neat. Spire.Doc for Java provides the ParagraphStyle class, allowing you to define the font name, size, style, and text color using a single object. After creating a style, you can easily apply it to format a paragraph according to your preferred settings.

The steps to set the font for a paragraph using Java are as follows:

  • Create a Document object.
  • Load a Word file, and add a paragraph to it.
  • Append text to the paragraph.
  • Create a ParagraphStyle object.
  • Get the CharacterFormat object using the ParagraphStyle.getCharacterFormat() method.
  • Set the font style, name, size and text color using the methods under the CharacterFormat object.
  • Add the style to the document using the Document.getStyles().add() method.
  • Apply the defined style to the paragraph using the Paragraph.applyStyle() method.
  • Save the document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

public class ApplyFontToParagraph {

    public static void main(String[] args) {

        // Create a Document instance
        Document document = new Document();

        // Load a Word document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        // Get the last section
        Section section = document.getLastSection();

        // Add a paragraph
        Paragraph paragraph = section.addParagraph();

        // Append text to the paragraph
        paragraph.appendText("Java's versatility and wide range of applications make it one of the most popular " +
                "programming languages in the world. Its strong community support and continuous evolution ensure " +
                "it remains relevant in modern software development.");

        // Create a ParagraphStyle object
        ParagraphStyle style = new ParagraphStyle(document);
        
        // Set the style name
        style.setName("MyStyle");
        
        // Set the font style, name, size and text color
        style.getCharacterFormat().setBold(false);
        style.getCharacterFormat().setTextColor(Color.blue);
        style.getCharacterFormat().setFontName("Times New Roman");
        style.getCharacterFormat().setFontSize(13f);

        // Add the style to document
        document.getStyles().add(style);

        // Apply the style to the paragraph
        paragraph.applyStyle(style.getName());

        // Apply the style to an existing paragraph
        // section.getParagraphs().get(1).applyStyle(style.getName());

        // Save the document to file
        document.saveToFile("output/ApplyFont.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

A paragraph in a document to which a defined font style has been applied

Apply Multiple Fonts to a Paragraph in Java

In certain situations, you might want to apply different fonts to various parts of the same paragraph to highlight important information. Spire.Doc for Java offers the TextRange class, which enables you to assign distinct styles to specific segments of text within a paragraph. To achieve this, ensure that the text requiring different styles is organized into separate text ranges.

The steps to apply multiple fonts in a paragraph using Java are as follows:

  • Create a Document object.
  • Load a Word file, and add a paragraph to it.
  • Append text to the paragraph using the Paragraph.appendText() method, which returns a TextRange object.
  • Append more text that needs to be styled differently to the paragraph and return different TextRange objects.
  • Create a ParagraphStyle object with the basic font information and apply it to the paragraph.
  • Change the font name, style, size and text color of the specified text range using the methods under the specific TextRange object.
  • Save the document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class ApplyMultipleFonts {

    public static void main(String[] args) {

        // Create a Document object
        Document document = new Document();

        // Load a Word document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        // Get the last section
        Section section = document.getLastSection();

        // Add a paragraph
        Paragraph paragraph = section.addParagraph();

        // Append text to the paragraph
        TextRange textRange1 = paragraph.appendText("Java's");
        TextRange textRange2 = paragraph.appendText(" versatility and wide range of applications make it ");
        TextRange textRange3 = paragraph.appendText("one of the most popular programming languages");
        TextRange textRange4 = paragraph.appendText(" in the world. Its strong community support and continuous evolution " +
                "ensure it remains relevant in modern software development.");

        // Create a ParagraphStyle object
        ParagraphStyle style = new ParagraphStyle(document);
        style.setName("MyStyle");
        style.getCharacterFormat().setBold(false);
        style.getCharacterFormat().setTextColor(Color.black);
        style.getCharacterFormat().setFontName("Times New Roman");
        style.getCharacterFormat().setFontSize(13f);

        // Add the style the document
        document.getStyles().add(style);

        // Apply the style to the paragraph
        paragraph.applyStyle(style.getName());

        // Change the font style of the specified text ranges
        textRange1.getCharacterFormat().setTextColor(Color.blue);
        textRange3.getCharacterFormat().setItalic(true);
        textRange3.getCharacterFormat().setTextColor(Color.red);
        
        // Change the font name and size if you want
        // textRange1.getCharacterFormat().setFontName("Arial");
        // textRange1.getCharacterFormat().setFontSize(15f);

        // Set the horizontal alignment
        paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);

        // Save the document to a docx file
        document.saveToFile("output/ApplyMultipleFonts.docx", FileFormat.Docx_2019);

        // Dispose resources
        document.dispose();
    }
}

A paragraph in a Word document with different font styles applied to different parts

Use a Private Font in a Word Document in Java

In creative fields like graphic design and marketing, incorporating private fonts in a Word document can enhance aesthetics, making it more engaging and visually unique. To add a custom font to a document, use the Document.getPrivateFontList().add() method. To ensure the document displays correctly on systems without the font installed, embed the font using the Document.setEmbedFontsInFile() method.

The steps to incorporate private fonts in a Word document are as follows:

  • Create a Document object.
  • Load a Word file, and add a paragraph to it.
  • Create a PrivateFontPath object, specifying the name and path of a private font.
  • Add the font to document using the Document.getPrivateFontList().add() method.
  • Embed fonts in the generated file by passing true to the Document.setEmbedFontsInFile() method.
  • Apply the font to the paragraph using the TextRange.getCharacterFormat().setFontName() method.
  • Save the document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

public class ApplyPrivateFont {

    public static void main(String[] args) {

        // Create a Document instance
        Document document = new Document();

        // Load a Word document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        // Get the last section
        Section section = document.getLastSection();

        // Add a paragraph
        Paragraph paragraph = section.addParagraph();

        // Append text to the paragraph
        TextRange textRange = paragraph.appendText("Java's versatility and wide range of applications make it one of the most popular " +
                "programming languages in the world. Its strong community support and continuous evolution ensure " +
                "it remains relevant in modern software development.");

        // Create a PrivateFontPath object, specifying font name and path
        PrivateFontPath fontPath = new PrivateFontPath();
        fontPath.setFontName("Otto");
        fontPath.setFontPath("C:\\Users\\Administrator\\Desktop\\Otto.ttf");

        // Add the private font to the document
        document.getPrivateFontList().add(fontPath);

        // Embed fonts in the generated file
        document.setEmbedFontsInFile(true);

        // Apply font to text range
        textRange.getCharacterFormat().setFontName("Otto");
        textRange.getCharacterFormat().setFontSize(28f);

        // Save the document to file
        document.saveToFile("output/ApplyPrivateFont.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

A paragraph in a Word document with a custom font applied

Change the Font of the Specified Text in Java

Changing the font of specific text can highlight key information, enhancing its visibility for readers. Spire.Doc for Java offers the Document.findAllString() method, allowing developers to search for a specified string within an existing document. Once the text is located, you can assign it to a TextRange object, which provides various APIs for formatting the text.

The steps to change the of the specified text in a Word document using Java are as follows:

  • Create a Document object.
  • Load a Word file.
  • Find all the occurrences of the specified string using the Document.findAllString() method.
  • Iterate through the occurrences.
    • Get the specific occurrence (TextSection) as a TextRange object.
    • Get the CharacterFormat object using the TextRange.getCharacterFormat() method.
    • Change the font name, style, size and text color of the text range using the methods under the CharacterFormat object.
  • Save the document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class ChangeFontOfText {

    public static void main(String[] args) {

        // Create a Document instance
        Document document = new Document();

        // Load a Word document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        // Find the text you wish to modify the font for
        TextSelection[] textSelections = document.findAllString("Rich Standard Library", false, true);

        // Iterate through the find results
        for (int i = 0; i < textSelections.length; i++) {

            // Get a specific text selection as a text range
            TextRange textRange = textSelections[i].getAsOneRange();

            // Change the text color and style
            textRange.getCharacterFormat().setTextColor(Color.blue);
            textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Dash);
            textRange.getCharacterFormat().setBold(true);

            // Change font name and size if you want
            // textRange.getCharacterFormat().setFontName("Calibri");
            // textRange.getCharacterFormat().setFontSize(18f);
        }

        // Save the result document
        document.saveToFile("output/ChangeFontOfText.docx", FileFormat.Docx_2019);

        // Dispose resources
        document.dispose();
    }
}

A paragraph within which specific text’s font style has been changed

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.

Adding a header to a PDF document is a useful way to display important information such as the document title, author, and page numbers. A header is a section of text or graphics that appears at the top of each page in a document and can be customized according to your needs. This feature is particularly helpful when creating reports, contracts, or other professional documents that require a consistent format. In this article, you will learn how to add a header to an existing PDF document in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.12.16</version>
    </dependency>
</dependencies>

Background Knowledge

When an existing PDF document is manipulated by Spire.PDF for Java, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a header to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the upper blank area of the page.

Java: Add a Header to an Existing PDF Document

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.

Add a Header to an Existing PDF Document in Java

Spire.PDF for Java allows users to draw text, images and shapes on a PDF page using PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and other similar methods. To add dynamic information to the header, such as page numbers, sections, dates, you need to resort to automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfSectionNumberField class, PdfCreationDateField class, etc. to achieve the dynamic addition of these data.

The following are the steps to add a header consisting of text, an image, a date, and a line to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Create font, pen and brush objects that will be used to draw text or shapes.
  • Draw text on the top blank area of a page using PdfPageBase.getCanvas().drawString() method.
  • Draw a line on the top blank area of a page using PdfPageBase.getCanvas().drawLine() method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image on the top blank area of a page using PdfPageBase.getCanvas().drawImage() method.
  • Create a PdfCreationDateField object that reflects the creation time of the document.
  • Draw the creation time on the top blank area of a page using PdfCreationDateField.draw() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfCreationDateField;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class AddHeaderToPdf {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\TargetMarket.pdf");

        //Load an image for the header
        PdfImage headerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\logo.png");

        //Get image width in pixel
        float width = headerImage.getWidth();

        //Convert pixel to point
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);

        //Specify text for the header
        String headerText = "E-iceblue Tech\nwww.e-iceblue.com";

        //Create a true type font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12),true);

        //Create a brush
        PdfBrush brush = PdfBrushes.getPurple();

        //Create a pen
        PdfPen pen = new PdfPen(brush, 1.0f);

        //Create a creation date field
        PdfCreationDateField creationDateField = new PdfCreationDateField(font, brush);
        creationDateField.setDateFormatString("yyyy-MM-dd");

        //Create a composite field to combine static string and date field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "creation time: {0}", creationDateField);
        compositeField.setLocation(new Point(55, 48));

        //Loop through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++)
        {
            //Get specific page
            PdfPageBase page = doc.getPages().get(i);

            //Draw the image on the top blank area
            page.getCanvas().drawImage(headerImage, page.getActualSize().getWidth() - pointWidth - 55, 20);

            //Draw text on the top blank area
            page.getCanvas().drawString(headerText, font, brush, 55, 20);

            //Draw a line on the top blank area
            page.getCanvas().drawLine(pen, new Point(55, 70), new Point((int)page.getActualSize().getWidth() - 55, 70));

            //Draw the composite field on the top blank area
            compositeField.draw(page.getCanvas());
        }

        //Save to file
        doc.saveToFile("output/AddHeader.pdf");
        doc.dispose();
    }
}

Java: Add a Header to an Existing PDF Document

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 82