HTML is a markup language for creating websites or other web applications. In daily work, you might need to convert HTML to images for various reasons, such as creating thumbnails of web pages to use in search engine results pages or social media posts, generating snapshots of your html files for archiving or other purposes, and so on. In this article, you will learn how to convert Html to JPG, PNG, or BMP images 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 HTML to JPG, PNG and BMP Images in C++
To complete the task, you’ll need to load an HTML file first and then convert it to images using Document->SaveImageToStreams() method. These images can also be further saved as JPEG, PNG, BMP, EMF, GIF or WMF image formats. The following are the detailed steps.
- Create a Document instance.
- Load a sample html file using Document->LoadFromFile(LPCWSTR_S filename, FileFormat::Html, XHTMLValidationType::None) method.
- Convert the html file to an image stream using Document->SaveImageToStreams() method.
- Convert the image stream to an Image object using Image::FromStream(intrusive_ptr<Stream> stream) method.
- Save the Image object as a JPEG, PNG, BMP, or other image formats using Image->Save(LPCWSTR_S filename, ImageFormat format) method.
- C++
#include "Spire.Doc.o.h" using namespace std; using namespace Spire::Doc; int main() { //Specify the input file path wstring inputFile = L"Data\\sample.html"; //Create a Document instance intrusive_ptr<Document> document = new Document(); //Load a sample html file from disk document->LoadFromFile(inputFile.c_str(), FileFormat::Html, XHTMLValidationType::None); //Convert the html to image streams intrusive_ptr<Stream> imageStream = document->SaveImageToStreams(0,ImageType::Bitmap); //Save the image stream as a PNG, JPG or BMP image intrusive_ptr<Image> image = Image::FromStream(imageStream); image->Save(L"HtmlToPNG.png", ImageFormat::GetPng()); image->Save(L"HtmlToJPG.jpg", ImageFormat::GetJpeg()); image->Save(L"HtmlToImage.bmp", ImageFormat::GetBmp()); document->Close(); imageStream->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.