C++: Convert PDF to Images
The PDF file format is ideal for most occasions. But still, you may encounter situations where you need to convert PDF to images. Once you convert a certain PDF page into an image, you can post it on social media, upload or transfer it in devices that can only display images, or embed it in your Word document or PowerPoint presentation. In this article, you will learn how to programmatically convert PDF to images in C++ using Spire.PDF for C++.
Install Spire.PDF for C++
There are two ways to integrate Spire.PDF 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.PDF for C++ in a C++ Application
Convert a Specific Page to an Image in C++
Spire.PDF for C++ offers the PdfDocument->SaveAsImage(int pageIndex) method to convert a particular page into image stream. The stream can be then saved as an image file with the desired extension like PNG, JPG, and BMP. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument->LoadFromFile() method.
- Convert a specific page into image stream using PdfDocument->SaveAsImage() method.
- Save the image steam as a JPG file using Stream->Save() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input and output file paths
wstring inputFile = L"C:\\Users\\Administrator\\Desktop\\sample.pdf";
wstring outputFile = L"C:\\Users\\Administrator\\Desktop\\Output\\ToImage";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFile.c_str());
//Convert a specific page as image
boost::intrusive_ptr<Stream> image = doc->SaveAsImage(0, PdfImageType::Bitmap);
//Write image to a .jpg file
wstring fileName = outputFile + L".jpg";
image->Save(fileName.c_str());
doc->Close();
delete doc;
}

Convert an Entire PDF to Multiple Images in C++
In order to save the whole PDF as separate individual images, you just need to put the conversion part inside a loop statement. The follows are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument->LoadFromFile() method.
- Loop through the pages in the document and convert each of them into image stream using PdfDocument->SaveAsImage(int pageIndex) method.
- Save the image steam as JPG files using Stream->Save() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input and output file paths
wstring inputFile = L"C:\\Users\\Administrator\\Desktop\\sample.pdf";
wstring outputFile = L"C:\\Users\\Administrator\\Desktop\\Output\\ToImg-";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFile.c_str());
//Iterate through the pages in the document
for (int i = 0; i < doc->GetPages()->GetCount(); i++) {
//Save a specific page as image
boost::intrusive_ptr<Stream> image = doc->SaveAsImage(i);
//Write image to a .jpg file
wstring fileName = outputFile + to_wstring(i) + L".jpg";
image->Save(fileName.c_str());
}
doc->Close();
delete doc;
}

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.
C++: Convert PowerPoint Presentation to PDF
When you need to share or present your PowerPoint presentations on different computers/devices, you may occasionally find that some content cannot be displayed properly. To avoid such incompatibility issues, a common method is to convert your PowerPoint document to PDF to ensure document integrity. In this article, you will learn how to convert a PowerPoint Presentation to PDF in C++ using Spire.Presentation for C++.
- Convert an Entire PowerPoint Presentation to PDF in C++
- Convert a Specific PowerPoint Slide to PDF in C++
- Convert a PowerPoint to PDF with Specific Page Size in C++
Install Spire.Presentation for C++
There are two ways to integrate Spire.Presentation 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.Presentation for C++ in a C++ Application
Convert an Entire PowerPoint Presentation to PDF in C++
The Presentation->SaveToFile(LPCWSTR_S fileName, FileFormat::PDF) method allows you to convert each slide in PowerPoint to a PDF page. The following are the steps to convert a whole PowerPoint presentation to PDF.
- Create a Presentation object.
- Load a PowerPoint presentation using Presentation->LoadFromFile() method.
- Save it to PDF using Presentation->SaveToFile(LPCWSTR_S fileName, FileFormat::PDF) method.
- C++
#include "Spire.Presentation.o.h";
using namespace Spire::Presentation;
using namespace std;
int main()
{
//Specify the input and output file paths
std::wstring inputFile = L"Data\\sample.pptx";
std::wstring outputFile = L"Output\\PowerPointToPDF.pdf";
//Create a Presentation object
intrusive_ptrPresentation> ppt = new Presentation();
//Load a PowerPoint document from disk
ppt->LoadFromFile(inputFile.c_str());
//Save the document to PDF
ppt->SaveToFile(outputFile.c_str(), FileFormat::PDF);
ppt->Dispose();
}

Convert a Specific PowerPoint Slide to PDF in C++
If you only want to convert a particular slide to PDF, you can use the ISlide->SaveToFile(LPCWSTR_S fileName, FileFormat::PDF) method provided by Spire.Presentation for C++. The following are the detailed steps.
- Create a Presentation object.
- Load a PowerPoint presentation using Presentation->LoadFromFile() method.
- Get a specified slide by index using Presentation->GetSlides()->GetItem(slideIndex) method.
- Save the slide to PDF using ISlide->SaveToFile(LPCWSTR_S fileName, FileFormat::PDF) method.
- C++
#include "Spire.Presentation.o.h";
using namespace Spire::Presentation;
using namespace std;
int main()
{
//Specify the input and output file paths
std::wstring inputFile = L"Data\\sample.pptx";
std::wstring outputFile = L"Output\\SlideToPDF.pdf";
//Create a Presentation object
intrusive_ptrPresentation> ppt = new Presentation();
//Load a PowerPoint document from disk
ppt->LoadFromFile(inputFile.c_str());
//Get the second slide
intrusive_ptr slide = ppt->GetSlides()->GetItem(1);
//Save the second slide to PDF
slide->SaveToFile(outputFile.c_str(), FileFormat::PDF);
ppt->Dispose();
}

Convert a PowerPoint to PDF with Specific Page Size in C++
Spire.Presentation for C++ also allows you to set a desired slide size and orientation for a PowerPoint document before converting it to PDF. The following are the steps to convert a PowerPoint to PDF with Specific Page Size (A4 slide size = 10.83x7.05 inch).
- Create a Presentation object.
- Load a PowerPoint presentation using Presentation->LoadFromFile() method.
- Set the slide size of the PowerPoint document using Presentation->GetSlideSize()->SetType() method.
- Set the slide orientation of the PowerPoint document using Presentation->GetSlideSize()->SetOrientation() method.
- Save the document to PDF using Presentation->SaveToFile(LPCWSTR_S fileName, FileFormat::PDF) method.
- C++
#include "Spire.Presentation.o.h";
using namespace Spire::Presentation;
using namespace std;
int main()
{
//Specify the input and output file paths
std::wstring inputFile = L"Data\\sample.pptx";
std::wstring outputFile = L"Output\\ToPdfWithSpecificPageSize.pdf";
//Create a Presentation object
intrusive_ptrPresentation> ppt = new Presentation();
//Load a PowerPoint document from disk
ppt->LoadFromFile(inputFile.c_str());
//Set the slide size to A4
ppt->GetSlideSize()->SetType(SlideSizeType::A4);
//Set the slide orientation to Landscape
ppt->GetSlideSize()->SetOrientation(SlideOrienation::Landscape);
//Save the document to PDF
ppt->SaveToFile(outputFile.c_str(), FileFormat::PDF);
ppt->Dispose();
}

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.
C++: Add Image Watermarks to PDF Documents
Watermarks are faded text or images that appear behind the existing content of a document. You can use them to indicate a document's state (confidential, draft, etc.), or add a subtle company logo. A watermark helps prove the origin of a document and discourage unauthorized copies or distribution. In this article, you will learn how to add image watermarks to PDF in C++ using Spire.PDF for C++.
Install Spire.PDF for C++
There are two ways to integrate Spire.PDF 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.PDF for C++ in a C++ Application
Add a Single Image Watermark to PDF in C++
The PdfPageBase->GetCanvas()->DrawImage() method provided by Spire.PDF for C++ allows developers to draw images at any position of a PDF page. The image can be faded by adjusting the transparency of the canvas to prevent it from overwriting the text. The detailed steps to add a single image watermark to PDF are as follows.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument->LoadFromFile() method.
- Get a specific page from the document using PdfDocument->GetPages()->GetItem() method.
- Set the transparency of the page using PdfPageBase->GetCanvas()->SetTransparency() method.
- Draw an image at the center of the page using PdfPageBase->GetCanvas()->DrawImage() method.
- Save the document to a different PDF file using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace std;
using namespace Spire::Pdf;
int main()
{
//Specify input file and output file paths
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.pdf";
wstring outputFilePath = L"C:\\Users\\Administrator\\Desktop\\ImageWatermark.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFilePath.c_str());
//Load an image
boost::intrusive_ptr image = PdfImage::FromFile(L"C:\\Users\\Administrator\\Desktop\\logo.png");
//Get image height and width
int imgHeight = image->GetHeight();
int imgWidth = image->GetWidth();
//Traverse through the pages in the document
for (size_t i = 0; i < doc->GetPages()->GetCount(); i++)
{
//Get a specific page
boost::intrusive_ptr page = doc->GetPages()->GetItem(i);
//Set the page transparency
page->GetCanvas()->SetTransparency(0.5);
//Get the page width and height
float pageWidth = page->GetActualSize()->GetWidth();
float pageHeight = page->GetActualSize()->GetHeight();
//Draw image at the center of the page
RectangleF* rect = new RectangleF((float)(pageWidth - imgWidth) / 2, (float)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
page->GetCanvas()->DrawImage(image, rect);
}
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}

Add a Tiled Image Watermark to PDF in C++
A tiled watermark effect can be achieved by using the PdfTilingBrush class. The tiling brush produces a tiled pattern that is repeated to fill a graphics area. The following are the steps to add a tiled image watermark to a PDF document.
- Create a custom method InsertTiledImagetWatermark(PdfPageBase* page, PdfImage* image, int rowNum, int columnNum) to add a tiled watermark to a PDF page. The parameter rowNum and columnNum specify the row number and column number of the tiled watermark.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument->LoadFromFile() method.
- Traverse through all pages in the document, and invoke the custom method InsertTiledImageWatermark() to apply watermark to each page.
- Save the document to another file using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace std;
using namespace Spire::Pdf;
static void InsertTiledImagetWatermark(PdfPageBase* page, PdfImage* image, int rowNum, int columnNum)
{
//Get page height and width
float height = page->GetActualSize()->GetHeight();
float width = page->GetActualSize()->GetWidth();
//Get image heigh and width
float imgHeight = image->GetHeight();
float imgWidth = image->GetWidth();
//Create a tiling brush
PdfTilingBrush* brush = new PdfTilingBrush(new SizeF(width / columnNum, height / rowNum));
//Set transparency
brush->GetGraphics()->SetTransparency(0.5f);
//Translate coordinate system to a certain position
brush->GetGraphics()->TranslateTransform((brush->GetSize()->GetWidth() - imgWidth) / 2, (brush->GetSize()->GetHeight() - imgHeight) / 2);
//Draw image on the brush at the specified coordinates
brush->GetGraphics()->DrawImage(image, 0.0, 0.0);
//Draw rectangle that covers the whole page with the brush
page->GetCanvas()->DrawRectangle(brush, 0, 0, width, height);
}
int main()
{
//Specify input file and output file paths
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.pdf";
wstring outputFilePath = L"C:\\Users\\Administrator\\Desktop\\TiledImageWatermark.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFilePath.c_str());
//Load an image
PdfImage* image = PdfImage::FromFile(L"C:\\Users\\Administrator\\Desktop\\small-logo.png");
//Traverse through the pages in the document
for (size_t i = 0; i < doc->GetPages()->GetCount(); i++)
{
//Get a specific page
PdfPageBase* page = doc->GetPages()->GetItem(i);
//Add tiled image watermark to the page
InsertTiledImagetWatermark(page, image, 4, 4);
}
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}

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.
C++: Convert Excel to HTML
Converting Excel to HTML makes it easier to embed your spreadsheet data on a website and also ensures that other people can view the document online in their browsers without opening Excel. In this article, you will learn how to convert Excel to HTML using Spire.XLS for C++.
- Convert an Entire Excel Workbook to HTML in C++
- Convert a Specific Worksheet to HTML with Images Embedded in C++
- Convert a Specific Worksheet to HTML Stream in C++
Install Spire.XLS for C++
There are two ways to integrate Spire.XLS 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.XLS for C++ in a C++ Application
Convert an Entire Excel Workbook to HTML in C++
The Workbook->SaveToHtml() method provided by Spire.XLS for C++ allows you to convert the whole workbook to HTML. The following are the detailed steps.
- Create a Workbook object.
- Load an Excel document using Workbook->LoadFromFile() method.
- Save the entire Excel workbook as an HTML file using Workbook->SaveToHtml() method.
- C++
#include "Spire.Xls.o.h"
using namespace Spire::Xls;
int main()
{
//Specify input file path and name
std::wstring data_path = L"Data\\";
std::wstring inputFile = data_path + L"input.xlsx";
//Specify output file path and name
std::wstring outputPath = L"Output\\";
std::wstring outputFile = outputPath + L"ToHtml.html";
//Create a Workbook object
intrusive_ptr<Workbook> workbook = new Workbook();
//Load an Excel document from disk
workbook->LoadFromFile(inputFile.c_str());
//Save the whole Excel workbook to Html
workbook->SaveToHtml(outputFile.c_str());
workbook->Dispose();
}

Convert a Specified Worksheet to HTML with Images Embedded in C++
If you want the images in a worksheet to be embedded into the HTML code while conversion, you can set the parameter of HTMLOptions->SetImageEmbedded() method to true. The following are the detailed steps.
- Create a Workbook object.
- Load an Excel document using Workbook->LoadFromFile() method.
- Get a specific worksheet using Workbook->GetWorksheets()->Get() method.
- Create an HTMLOptions instance and enable image embedding using HTMLOptions->SetImageEmbedded(true) method.
- Save the worksheet to HTML with image embedded using Worksheet->SaveToHtml(LPCWSTR_S fileName, HTMLOptions* saveOption) method.
- C++
#include "Spire.Xls.o.h"
using namespace Spire::Xls;
int main()
{
//Specify input file path and name
std::wstring data_path = L"Data\\";
std::wstring inputFile = data_path + L"sample.xlsx";
//Specify output file path and name
std::wstring outputPath = L"Output\\";
std::wstring outputFile = outputPath + L"ExcelToHtml.html";
//Create a Workbook object
intrusive_ptr<Workbook> workbook = new Workbook();
//Load an Excel document from disk
workbook->LoadFromFile(inputFile.c_str());
//Get the first worksheet
intrusive_ptr<Worksheet> sheet = dynamic_pointer_cast<Worksheet>(workbook->GetWorksheets()->Get(0));
//Set embedded image as true
intrusive_ptr<HTMLOptions> options = new HTMLOptions();
options->SetImageEmbedded(true);
//Save the worksheet to HTML
sheet->SaveToHtml(outputFile.c_str(), options);
workbook->Dispose();
}

Convert a Specified Worksheet to HTML Stream in C++
Spire.XLS for C++ also allows you to convert a worksheet to HTML stream using Worksheet->SaveToHtml(Stream* stream, HTMLOptions* saveOption) method. The following are the detailed steps.
- Create a Workbook object.
- Load an Excel document using Workbook->LoadFromFile() method.
- Get a specific worksheet using Workbook->GetWorksheets()->Get() method.
- Create an HTMLOptions instance and enable image embedding using HTMLOptions->SetImageEmbedded(true) method.
- Create a stream and save the worksheet to HTML stream with image embedded using Worksheet->SaveToHtml(Stream* stream, HTMLOptions* saveOption) method.
- C++
#include "Spire.Xls.o.h"
using namespace Spire::Xls;
int main()
{
//Specify input file path and name
std::wstring data_path = L"Data\\";
std::wstring inputFile = data_path + L"sample.xlsx";
//Specify output file path and name
std::wstring outputPath = L"Output\\";
std::wstring outputFile = outputPath + L"ToHtmlStream.html";
//Create a Workbook object
intrusive_ptr<Workbook> workbook = new Workbook();
//Load an Excel document from disk
workbook->LoadFromFile(inputFile.c_str());
//Get the first worksheet
intrusive_ptr<Worksheet> sheet = dynamic_pointer_cast<Worksheet>(workbook->GetWorksheets()->Get(0));
//Set embedded image as true
intrusive_ptr<HTMLOptions> options = new HTMLOptions();
options->SetImageEmbedded(true);
//Create a stream
intrusive_ptr<Stream> stream = new Stream();
//Save worksheet to html stream
sheet->SaveToHtml(stream, options);
workbook->Dispose();
stream->Save(outputFile.c_str());
}
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.
C++: Add Text Watermarks to PDF Documents
As increasingly diverse types of documents are created in PDF, you may find yourself with a need to protect confidential information. Although many other PDF security options are available to keep confidential information secure, the most common approach is to add a custom watermark to the PDF document. In this article, you will learn how to add a single-line or multi-line text watermark to PDF in C++ using Spire.PDF for C++.
Install Spire.PDF for C++
There are two ways to integrate Spire.PDF 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.PDF for C++ in a C++ Application
Add a Single-Line Text Watermark to PDF in C++
Spire.PDF for C++ does not provide an interface or a class responsible for inserting watermarks into PDF files. You could, however, draw text like "confidential", "do not copy", or "draft" on each page to mimic the watermark effect. The following are the steps to add a single-line text watermark to a PDF document.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument->LoadFromFile() method.
- Get a specific page from the document using PdfDocument->GetPages()->GetItem() method.
- Translate the coordinate system to the specified coordinate using PdfPageBase->GetCanvas()->TraslateTransform() method.
- Rotate the coordinate system 45 degrees counterclockwise using PdfPageBase->GetCanvas()->RotateTransform() method. This step and the step above make sure that the watermark will appear in the middle of the page with an angle of 45 degrees.
- Draw a text watermark on the page using PdfPageBase->GetCanvas()->DrawString() method.
- Save the document to a different PDF file using PdfDocument->SaveToFile() method.
- C++
"#include ""Spire.Pdf.o.h"";
using namespace std;
using namespace Spire::Pdf;
using namespace Spire::Common;
int main()
{
//Specify input file and output file paths
wstring inputFilePath = L""C:\\Users\\Administrator\\Desktop\\sample.pdf"";
wstring outputFilePath = L""Output\\SingleLineTextWatermark.pdf"";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFilePath.c_str());
//Create a true type font
PdfTrueTypeFont* font = new PdfTrueTypeFont(L""Arial"", 50.0f, PdfFontStyle::Bold, true);
//Create a brush
PdfBrush* brush = PdfBrushes::GetDarkGray();
//Specify watermark text
wstring text = L""CONFIDENTIAL"";
//Measure the text size
SizeF textSize = font->MeasureString(text.c_str());
//Calculate two offsets, which are used to calculate the translation amount of coordinate system
float offset1 = (float)(textSize.GetWidth() * sqrt(2) / 4);
float offset2 = (float)(textSize.GetHeight() * sqrt(2) / 4);
//Traverse through the pages in the document
for (size_t i = 0; i < doc->GetPages()->GetCount(); i++)
{
//Get a specific page
PdfPageBase* page = doc->GetPages()->GetItem(i);
//Set the page transparency
page->GetCanvas()->SetTransparency(0.8);
//Translate the coordinate system to a specified coordinate
page->GetCanvas()->TranslateTransform(page->GetCanvas()->GetSize()->GetWidth() / 2 - offset1 - offset2, page->GetCanvas()->GetSize()->GetHeight() / 2 + offset1 - offset2);
//Rotate the coordinate system 45 degrees counterclockwise
page->GetCanvas()->RotateTransform(-45);
//Draw watermark text on the page
page->GetCanvas()->DrawString(text.c_str(), font, brush, 0, 0, new PdfStringFormat(PdfTextAlignment::Left));
}
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}"

Add a Tiled Text Watermark to PDF in C++
To achieve the tiled watermark effect, you can make use of the PdfTilingBrush class. The tiling brush produces a tiled pattern that is repeated to fill a graphics area. The following are the steps to add a tiled text watermark to a PDF document.
- Create a custom method InsertTiledTextWatermark(PdfPageBase* page, wstring watermarkText, PdfTrueTypeFont* font, int rowNum, int columnNum) to add a tiled watermark to a PDF page. The parameter rowNum and columnNum specify the row number and column number of the tiled watermark.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument->LoadFromFile() method.
- Traverse through all pages in the document, and call the custom method InsertTiledTextWatermark() to apply watermark to each page.
- Save the document to another file using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace std;
using namespace Spire::Pdf;
static void InsertTiledTextWatermark(PdfPageBase* page, wstring watermarkText, PdfTrueTypeFont* font, int rowNum, int columnNum)
{
//Measure text size
SizeF textSize = font->MeasureString(watermarkText.c_str());
//Calculate two offsets, which are used to calculate the translation amount of coordinate system
float offset1 = (float)(textSize.GetWidth() * sqrt(2) / 4);
float offset2 = (float)(textSize.GetHeight() * sqrt(2) / 4);
//Get page height and width
float height = page->GetActualSize()->GetHeight();
float width = page->GetActualSize()->GetWidth();
//Create a tiling brush
PdfTilingBrush* brush = new PdfTilingBrush(new SizeF(width / columnNum, height / rowNum));
brush->GetGraphics()->SetTransparency(0.5f);
brush->GetGraphics()->TranslateTransform(brush->GetSize()->GetWidth() / 2 - offset1 - offset2, brush->GetSize()->GetHeight() / 2 + offset1 - offset2);
brush->GetGraphics()->RotateTransform(-45);
//Draw watermark text on the brush
brush->GetGraphics()->DrawString(watermarkText.c_str(), font, PdfBrushes::GetRed(), 0, 0, new PdfStringFormat(PdfTextAlignment::Left));
//Draw a rectangle (that covers the whole page) using the tiling brush
page->GetCanvas()->DrawRectangle(brush, new RectangleF(new PointF(0, 0), page->GetActualSize()));
}
int main()
{
//Specify input file and output file paths
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.pdf";
wstring outputFilePath = L"Output\\MultiLineTextWatermark.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputFilePath.c_str());
//Specify watermark text
wstring text = L"CONFIDENTIAL";
//Creat a true type font
PdfTrueTypeFont* font = new PdfTrueTypeFont(L"Arial", 20.0f, PdfFontStyle::Bold, true);
//Traverse through the pages in the document
for (size_t i = 0; i < doc->GetPages()->GetCount(); i++)
{
//Call the custom method to insert multi-line text watermark
boost::intrusive_ptr page = doc->GetPages()->GetItem(i);
InsertTiledTextWatermark(page.get(), text.c_str(), font, 3, 3);"
}
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}

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.
C++: Add or Delete Attachments in PDF Documents
Adding documents as attachments to PDF brings you a lot of convenience. For example, you can transfer multiple documents as a single document; you can open another file inside a PDF document without needing to find the document from other places; you reduce the possibility of losing documents referenced in the PDF document.
Spire.PDF for C++ allows you to attach files in two ways:
- Document Level Attachment (or Regular Attachment): A document-level attachment refers to the attachment that’s added to the Attachment tab and cannot be found on a specific page.
- Annotation Attachment: An annotation attachment refers to the attachment that’s added to a specific position of a page. Annotation attachments are shown as a paper clip icon on the page; reviewers can double-click the icon to open the file.
This article will show you how to add or delete regular attachments and annotation attachments in a PDF document in C++ using Spire.PDF for C++.
- Add a Regular Attachment to PDF in C++
- Add an Annotation Attachment to PDF in C++
- Delete Regular Attachments in PDF in C++
- Delete Annotation Attachments in PDF in C++
Install Spire.PDF for C++
There are two ways to integrate Spire.PDF 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.PDF for C++ in a C++ Application
Add a Regular Attachment to PDF in C++
To add a regular attachment, use PdfDocument->GetAttachments()->Add() method. The following are the detailed steps.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument->LoadFromFile() method.
- Create a PdfAttachment object based on an external file.
- Add the attachment to PDF using PdfDocument->GetAttachments()->Add() method.
- Save the document to another PDF file using PdfDocument.SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input file path
wstring inputPdfPath = L"C:\\Users\\Administrator\\Desktop\\Sample.pdf";
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\Data.xlsx";
//Specify output file path
wstring outputFilePath = L"Output\\Attachment.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a sample PDF file
doc->LoadFromFile(inputPdfPath.c_str());
//Create a PdfAttachment object based on an external file
PdfAttachment* attachment = new PdfAttachment(inputFilePath.c_str());
//Add the attachment to PDF
doc->GetAttachments()->Add(attachment);
//Save to file
doc->SaveToFile(outputFilePath.c_str());
delete doc;
}

Add an Annotation Attachment to PDF in C++
An annotation attachment is represented by the PdfAttachmentAnnotation class. You need to create an instance of the class based on an external file, and then add it to a specific page using PdfPageBase->GetAnnotationsWidget()->Add() method. The following are the detailed steps.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument->LoadFromFile() method.
- Get a specific page to add annotation using PdfDocument->GetPages()->GetItem() method.
- Create a PdfAttachmentAnnotation object based on an external file.
- Add the annotation attachment to the page using PdfPageBase->GetAnnotationsWidget->Add() method.
- Save the document using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input file path
wstring inputPdfPath = L"C:\\Users\\Administrator\\Desktop\\Attachment.pdf";
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\Report.docx";
//Specify output file path
wstring outputFilePath = L"Output\\AnnotationAttachment.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a sample PDF file
doc->LoadFromFile(inputPdfPath.c_str());
//Get a specific page
boost::intrusive_ptr<PdfPageBase> page = doc->GetPages()->GetItem(0);
//Draw a label on PDF
wstring label = L"Here is the report:";
PdfTrueTypeFont* font = new PdfTrueTypeFont(L"Arial", 13.0f, PdfFontStyle::Bold, true);
float x = 35;
float y = doc->GetPages()->GetItem(0)->GetActualSize()->GetHeight() - 220;
page->GetCanvas()->DrawString(label.c_str(), font, PdfBrushes::GetRed(), x, y);
//Convert the file to be attached to stream
ifstream is1(inputFilePath.c_str(), ifstream::in | ios::binary);
is1.seekg(0, is1.end);
int length1 = is1.tellg();
is1.seekg(0, is1.beg);
char* buffer1 = new char[length1];
is1.read(buffer1, length1);
Stream* stream = new Spire::Pdf::Stream((unsigned char*)buffer1, length1);
boost::intrusive_ptr <SizeF> size = font->MeasureString(label.c_str());
RectangleF* bounds = new RectangleF((float)(x + size->GetWidth() + 5), (float)y, 10, 15);
//Create a PdfAttachmentAnnotation object based on the file
PdfAttachmentAnnotation* annotation = new PdfAttachmentAnnotation(bounds, L"Report.docx", stream);
annotation->SetColor(new PdfRGBColor(Spire::Pdf::Color::GetDarkOrange()));
annotation->SetFlags(PdfAnnotationFlags::ReadOnly);
annotation->SetIcon(PdfAttachmentIcon::Graph);
annotation->SetText(L"Click here to open the file");
//Add the attachment annotation to PDF
page->GetAnnotationsWidget()->Add(annotation);
//Save to file
doc->SaveToFile(outputFilePath.c_str());
delete doc;
}

Delete Regular Attachments in PDF in C++
The PdfDocument->GetAttachments() method returns a collection of regular attachments of a PDF document. A specific attachment or all attachments can be removed by using PdfAttachmentCollection->RemoveAt() method or PdfAttachmentCollection->Clear() method. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument->LoadFromFile() method.
- Get the attachment collection from the document using PdfDocument->GetAttachments() method.
- Remove a specific attachment using PdfAttachmentCollection->RemoveAt() method. To remove all attachments at once, use PdfAttachmentCollection->Clear() method.
- Save the document using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input file path
wstring inputPdfPath = L"C:\\Users\\Administrator\\Desktop\\Sample.pdf";
//Specify output file path
wstring outputFilePath = L"Output\\DeleteAttachments.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputPdfPath.c_str());
//Get all attachments
boost::intrusive_ptr<PdfAttachmentCollection> attachments = doc->GetAttachments();
//Delete all attachments
attachments->Clear();
//Delete a specific attachment
//attachments->RemoveAt(0);
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}
Delete Annotation Attachments in PDF in C++
The annotation is a page-based element. You can get annotations from a specific page using PdfPageBase->GetAnnotationsWidget() method, and determine if a certain annotation is an annotation attachment. After that, remove the annotation attachment from the annotation collection using PdfAnnotationCollection->Remove() method. The following are the detailed steps.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument->LoadFromFile() method.
- Get the annotation collection from a specific page using PdfPageBase->GetAnnotationsWidget() method.
- Determine if an annotation is an instance of PdfAttachmentAnnotationWidget. If yes, remove the annotation attachment using PdfAnnotationCollection->Remove() method.
- Save the document using PdfDocument->SaveToFile() method.
- C++
#include "Spire.Pdf.o.h";
using namespace Spire::Pdf;
using namespace std;
int main() {
//Specify input file path
wstring inputPdfPath = L"C:\\Users\\Administrator\\Desktop\\AnnotationAttachment.pdf";
//Specify output file path
wstring outputFilePath = L"Output\\DeleteAnnotationAttachments.pdf";
//Create a PdfDocument object
PdfDocument* doc = new PdfDocument();
//Load a PDF file
doc->LoadFromFile(inputPdfPath.c_str());
//Loop through the pages
for (int i = 0; i < doc->GetPages()->GetCount(); i++)
{
//Get the annotation collection
boost::intrusive_ptr <PdfAnnotationCollection> annotationCollection = doc->GetPages()->GetItem(i)->GetAnnotationsWidget();
//Loop through the annotations
for (int j = 0; j < annotationCollection->GetCount(); j++)
{
//Get a specific annotation
boost::intrusive_ptr <PdfAnnotation> annotation = annotationCollection->GetItem(j);
//Determine if the annotation is an instance of PdfAttachmentAnnotationWidget
wstring content;
wchar_t nm_w[100];
swprintf(nm_w, 100, L"%hs", typeid(PdfAttachmentAnnotationWidget).name());
LPCWSTR_S newName = nm_w;
if (wcscmp(newName, annotation->GetInstanceTypeName()) == 0) {
//Remove the annotation attachment
annotationCollection->RemoveAt(j);
}
}
}
//Save the document
doc->SaveToFile(outputFilePath.c_str());
doc->Close();
delete doc;
}
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.
C++: Add Background Color or Picture to Word Documents
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++.
- Add a Background Color to Word in C++
- Add a Gradient Background to Word in C++
- Add a Background Picture to Word in 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 "Spire.Doc.o.h"
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(L"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(L"AddBackgroundColor.docx", FileFormat::Docx2013);
document->Close();
}

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 "Spire.Doc.o.h"
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(L"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(L"AddGradientBackground.docx", FileFormat::Docx2013);
document->Close();
}

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 "Spire.Doc.o.h"
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(L"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(L"background.png");
//Save the result document
document->SaveToFile(L"AddBackgroundPicture.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.
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++.
- Insert a Page Break after a Specific Paragraph in Word in C++
- Insert a Page Break after a Specific Text in Word in C++
- Remove Page Breaks in a Word Document in 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 "Spire.Doc.o.h"
using namespace Spire::Doc;
int main() {
//Specify input file path and name
std::wstring input_path = L"Data\\";
std::wstring inputFile = input_path + L"Input.docx";
//Specify output file path and name
std::wstring output_path = L"Output\\";
std::wstring outputFile = output_path + L"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()->GetItemInSectionCollection(0);
//Get the 2nd paragraph in the section
intrusive_ptr <Paragraph> paragraph = section->GetParagraphs()->GetItemInParagraphCollection(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();
}

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 "Spire.Doc.o.h"
using namespace Spire::Doc;
int main() {
//Specify input file path and name
std::wstring input_path = L"Data\\";
std::wstring inputFile = input_path + L"Input.docx";
//Specify output file path and name
std::wstring output_path = L"Output\\";
std::wstring outputFile = output_path + L"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(L"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();
}

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 "Spire.Doc.o.h"
using namespace Spire::Doc;
int main() {
//Specify input file path and name
std::wstring input_path = L"Data\\";
std::wstring inputFile = input_path + L"InsertPageBreak.docx";
//Specify output file path and name
std::wstring output_path = L"Output\\";
std::wstring outputFile = output_path + L"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()->GetItemInSectionCollection(0)->GetParagraphs()->GetCount(); j++)
{
intrusive_ptr<Paragraph> p = document->GetSections()->GetItemInSectionCollection(0)->GetParagraphs()->GetItemInParagraphCollection(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();
}

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.
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++.
- Convert Doc or Docx to PDF
- Convert Word to PDF with Bookmarks
- Convert Word to PDF with Fonts Embedded
- Set Image Quality When Converting Word to PDF
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 "Spire.Doc.o.h";
using namespace Spire::Doc;
using namespace std;
int main() {
//Specify input file path
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.docx";
//Specify output file path and name
wstring outputPath = L"Output\\";
wstring outputFile = outputPath + L"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();
}

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 "Spire.Doc.o.h";
using namespace Spire::Doc;
using namespace std;
int main() {
//Specify input file path
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.docx";
//Specify output file path and name
wstring outputPath = L"Output\\";
wstring outputFile = outputPath + L"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();
}

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 "Spire.Doc.o.h";
using namespace Spire::Doc;
using namespace std;
int main() {
//Specify input file path
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.docx";
//Specify output file path and name
wstring outputPath = L"Output\\";
wstring outputFile = outputPath + L"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();
}

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 "Spire.Doc.o.h";
using namespace Spire::Doc;
using namespace std;
int main() {
//Specify input file path
wstring inputFilePath = L"C:\\Users\\Administrator\\Desktop\\sample.docx";
//Specify output file path and name
wstring outputPath = L"Output\\";
wstring outputFile = outputPath + L"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.
C++: Extract Text and Images from Word Documents
Extracting text and images is a common requirement while working with Word documents. This will help you to save useful content out of the original document to re-use in a new document or for other purposes. In this article, you will learn how to extract text or images from 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
Extract Text from a Word Document in C++
To extract the text content from an existing Word document, Spire.Doc for C++ provides the Document->GetText() method. The following are steps to extract text and save in a TXT file.
- Create a Document instance.
- Load a sample Word document using Document->LoadFromFile() method.
- Get text from the document using Document->GetText() method.
- Create a new txt file and write the extracted text to the file.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main() {
//Specify input file path and name
std::wstring data_path = L"Data\\";
std::wstring inputFile = data_path + L"input.docx";
//Specify output file path and name
std::wstring outputPath = L"Output\\";
std::wstring outputFile = outputPath + L"GetText.txt";
//Create a Document instance
intrusive_ptr<Document> document = new Document();
//Load a sample Word document from disk
document->LoadFromFile(inputFile.c_str());
//Get text from the document
std::wstring text = document->GetText();
//Create a new TXT File to save the extracted text
std::wofstream write(outputFile);
write << text;
write.close();
document->Close();
}

Extract Images from a Word Document in C++
For a Word document with a lot of images, manually saving these images one by one is quite time-consuming. Below are steps to extract all images at once using Spire.Doc for C++.
- Load a sample Word document using Document->LoadFromFile() method.
- Append the document to the end of the deque, and then create a vector of images list.
- Traverse through all child objects of the document.
- Determine whether the object type is picture. If yes, get each image using DocPicture->GetImage() method and add it to the list.
- Save the extracted images out of the document in a specified output file path.
- C++
#include "Spire.Doc.o.h"
#include <deque>
using namespace Spire::Doc;
int main() {
//Specify input file path and name
std::wstring data_path = L"Data\\";
std::wstring inputFile = data_path + L"input.docx";
//Specify output file path and name
std::wstring outputPath = L"Output\\";
std::wstring outputFile = outputPath + L"ExtractImage/";
//Load a sample Word document
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFile.c_str());
//Append the document to the end of the deque
std::deque<intrusive_ptr<ICompositeObject>> nodes;
nodes.push_back(document);
//Create a vector of images list
std::vector<std::vector<byte>> images;
//Traverse through all child objects of the document
while (nodes.size() > 0)
{
intrusive_ptr<ICompositeObject> node = nodes.front();
nodes.pop_front();
for (int i = 0; i < node->GetChildObjects()->GetCount(); i++)
{
intrusive_ptr<IDocumentObject> child = node->GetChildObjects()->GetItem(i);
if (child->GetDocumentObjectType() == DocumentObjectType::Picture)
{
intrusive_ptr<DocPicture> picture = Object::Dynamic_cast<DocPicture>(child);
std::vector<byte> imageByte = picture->GetImageBytes();
images.push_back(imageByte);
}
else if (Object::CheckType<ICompositeObject>(child))
{
nodes.push_back(boost::dynamic_pointer_cast<ICompositeObject>(child));
}
}
}
//Save the images out of the document
for (size_t i = 0; i < images.size(); i++)
{
std::wstring fileName = L"Image-" + std::to_wstring(i) + L".png";
std::ofstream outFile(fileName, std::ios::binary);
if (outFile.is_open())
{
outFile.write(reinterpret_cast<const char*>(images[i].data()), images[i].size());
outFile.close();
}
}
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.