在这个简短的主题中,我们将学习如何使用 C++ 将 Word 转换为 PDF。您可以通过使用简单的 API 调用更改其外观和其他属性来自定义输出 PDF,并在 C++** 中从 DOCX 生成 PDF,可以在浏览器或任何其他查看器中查看。
使用 C++ 将 Word 转换为 PDF 的步骤
- 从 NuGet 包管理器安装 Aspose.Words for C++
- 包括 Aspose.Words 命名空间和所有必要的头文件
- 使用 Document class,加载源 Word 文件以在 C++ 中导出为 PDF
- 实例化 PdfSaveOptions 设置 PDF 的页面、页面模式和合规模式
- 使用 Save 方法将 DOCX 文件保存为 PDF
在上述步骤中,您可以使用简单的 API 调用将 Word 导出为 C++ 中的 PDF。从磁盘加载文档后,您可以使用 PdfSaveOptions 类自定义输出 PDF,并为导出的 PDF 设置页面范围、页面模式和 PDF 合规性。最后,我们将把 PDF 保存在磁盘或 MemoryStream 中。
在 C++ 中从 DOCX 生成 PDF 的代码
#pragma once | |
#include <cstdint> | |
#include <iostream> | |
#include <Aspose.Words.Cpp/License.h> | |
#include <Aspose.Words.Cpp/Document.h> | |
#include <Aspose.Words.Cpp/Range.h> | |
#include <Aspose.Words.Cpp/Saving/PageSet.h> | |
#include <Aspose.Words.Cpp/Saving/PdfSaveOptions.h> | |
#include <Aspose.Words.Cpp/Saving/SaveOutputParameters.h> | |
#include <Aspose.Words.Cpp/Saving/PageSet.h> | |
#include <Aspose.Words.Cpp/Saving/PdfPageMode.h> | |
#include <Aspose.Words.Cpp/Saving/PdfCompliance.h> | |
#include <system/enumerator_adapter.h> | |
#include <system/smart_ptr.h> | |
#include <system/shared_ptr.h> | |
#include <system/io/path.h> | |
using namespace Aspose::Words::Saving; | |
using namespace Aspose::Words; | |
using namespace Aspose::Words::Replacing; | |
using System::MakeObject; | |
using System::SharedPtr; | |
using System::String; | |
class WordToPDFEx | |
{ | |
public: | |
static void WordToPDF() | |
{ | |
// Load and Set API License | |
System::String LicFilePath = u"Aspose.Total.Net.lic"; | |
SharedPtr<Aspose::Words::License> WordsCPPLicenseForTable = System::MakeObject<Aspose::Words::License>(); | |
// Setting product license | |
WordsCPPLicenseForTable->SetLicense(LicFilePath); | |
// Open the DOCX file using Document class for saving as PDF | |
SharedPtr<Document> sampleDocx = MakeObject<Document>(u"TestAspose.docx"); | |
// Instantiate the PdfSaveOptions class object before converting the Docx to PDF | |
SharedPtr <PdfSaveOptions> options = MakeObject <PdfSaveOptions>(); | |
System::ArrayPtr <int32_t> pages = System::MakeObject<System::Array<int32_t>>(2); | |
pages[0] = 1; | |
pages[1] = 2; | |
SharedPtr <PageSet> pageSet = MakeObject<PageSet>(pages); | |
// Set the page numbers of the document to be rendered to output PDF | |
options->set_PageSet(pageSet); | |
// Configuring the full screen page mode while opening it in a viewer | |
options->set_PageMode(PdfPageMode::FullScreen); | |
// Set the output PDF document compliance mode | |
options->set_Compliance(PdfCompliance::Pdf17); | |
// Save the DOCX as PDF file using the above mentioned options | |
sampleDocx->Save(u"Output.pdf", options); | |
} | |
}; |
上面的示例 *在 C++ 中将 Word 转换为 PDF *。 PDF 的呈现首先从磁盘加载 Word 文件。然后在后续步骤中,我们使用 PdfSaveOptions 类来设置不同的 PDF 选项。您还可以通过设置其他可选设置来自定义 PDF,例如文本内容压缩、缩放行为、缩放系数、轮廓选项、使用抗锯齿的选项等等。最后,我们将生成的 PDF 保存在磁盘上。
我们在这里学习了如何使用 C++* 将 Word 转换为 PDF。如果您有兴趣了解如何将 Word 文件转换为 MD 文件格式,请参阅 如何使用 C++ 将 Word 转换为 Markdown 上的文章。