将文档转换为图像

有时需要获取图像而不是其他格式的文档,例如DOCX或PDF。 例如,您需要将任何文档页面的预览添加到您的网站或应用程序,或创建文档的"扫描"以发送发票。 这是您可能需要将任何supported load format中的文档转换为任何supported save format中的图像的时候。

转换为图像格式

与已经描述的所有转换示例一样,您需要以任何支持的格式创建新文档或加载现有文档,进行必要的更改,并以任何可用的图像格式保存,例如JPEG,PNG或BMP。

下面的代码示例演示如何将DOCX转换为JPEG:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(MyDir + u"TestDoc.docx");
// Save the document in JPEG format.
doc->Save(ArtifactsDir + u"SaveDocx2Jpeg.jpeg");

转换为图像时指定保存选项

Aspose.Words为您提供ImageSaveOptions类,它可以更好地控制如何以各种图像格式保存文档。 此类的某些属性继承或重载基类的属性,如FixedPageSaveOptionsSaveOptions,但也有特定于保存图像的选项。

可以使用PageSet属性指定要转换为图像格式的页面。 例如,如果您只需要第一个或特定页面的预览,则可以应用它。

还可以使用以下属性控制输出图像质量和像素格式– HorizontalResolution, VerticalResolution, Resolution, Scale, PixelFormat, 以及设置图像颜色设置,使用以下属性– ImageBrightness, ImageColorMode, ImageContrast, PaperColor.

还有一些适用于特定格式的属性,例如JpegQualityTiffCompression

下面的代码示例演示如何通过应用一些其他设置来创建第一个文档页面的预览:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Load the document from disk.
auto doc = System::MakeObject<Document>(inputDataDir + u"Rendering.doc");
auto imageSaveOptions = System::MakeObject<ImageSaveOptions>(SaveFormat::Jpeg);
// Set the "PageSet" to "0" to convert only the first page of a document.
auto pageRange = System::MakeObject<PageRange>(0, 0);
imageSaveOptions->set_PageSet(System::MakeObject<PageSet>(System::MakeArray<System::SharedPtr<PageRange>>({ pageRange })));
// Change the image's brightness and contrast.
// Both are on a 0-1 scale and are at 0.5 by default.
imageSaveOptions->set_ImageBrightness(0.3f);
imageSaveOptions->set_ImageContrast(0.7f);
// Change the horizontal resolution.
// The default value for these properties is 96.0, for a resolution of 96dpi.
imageSaveOptions->set_HorizontalResolution(72.0f);
// Save the document in JPEG format.
doc->Save(outputDataDir + u"SaveDocx2Jpeg.jpeg", imageSaveOptions);