使用案例
使用案例
本指南展示了 Aspose.PDF FOSS for C++ 的真实使用案例,包括文档生成、PDF 转图像转换、文本提取、安全分发以及 AcroForm 数据收集。该库仅链接 C++ 标准库,无需其他依赖,并且需要 C++20 编译器。
文档生成
通过向新的 Document 添加页面并保存结果,從頭構建 PDF。此模式是发票生成、证书打印和报表生产流水线的基础:
#include <aspose/pdf/document.hpp>
int main() {
Aspose::Pdf::Document doc;
doc.Pages().Add();
doc.SetTitle("Monthly Report");
doc.Save("report.pdf");
}PDF 转图像转换
将页面渲染为栅格图像,用于缩略图、可打印输出或视觉回归基准。PngDevice、JpegDevice、BmpDevice 和 TiffDevice 每次在给定分辨率下处理单页:
#include <aspose/pdf/document.hpp>
#include <aspose/pdf/png_device.hpp>
#include <aspose/pdf/resolution.hpp>
#include <fstream>
int main() {
Aspose::Pdf::Document doc("input.pdf");
Aspose::Pdf::Devices::PngDevice png(Aspose::Pdf::Devices::Resolution(150));
std::ofstream out("page1.png", std::ios::binary);
png.Process(doc.Pages()[1], out);
}文本提取与索引
使用 TextAbsorber 提取文档的完整文本,以用于搜索索引、数据挖掘流水线或测试套件中的自动内容验证:
#include <aspose/pdf/document.hpp>
#include <aspose/pdf/text_absorber.hpp>
#include <iostream>
int main() {
Aspose::Pdf::Document doc("input.pdf");
Aspose::Pdf::Text::TextAbsorber absorber;
absorber.Visit(doc);
std::cout << absorber.Text() << "\n";
}安全文档分发
在分发前使用不同的用户密码和拥有者密码对文档进行加密。用户密码用于打开文件;拥有者密码则控制诸如打印和内容提取等权限:
#include <aspose/pdf/document.hpp>
int main() {
Aspose::Pdf::Document doc("report.pdf");
doc.Encrypt("user-password", "owner-password",
Aspose::Pdf::Permissions(),
Aspose::Pdf::CryptoAlgorithm::AESx256);
doc.Save("report-secured.pdf");
}AcroForm 数据收集
通过遍历 Form.Fields() 并打印每个字段的名称和当前值,读取已填写 PDF 表单的提交值——这对于在没有单独表单提交服务器的情况下处理已填写的申请表非常有用:
#include <aspose/pdf/document.hpp>
#include <aspose/pdf/forms/form.hpp>
#include <iostream>
int main() {
Aspose::Pdf::Document doc("submitted-form.pdf");
auto& form = doc.Form();
for (auto* field : form.Fields()) {
std::cout << field->PartialName() << " = " << field->Value() << "\n";
}
}