You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PoDoFo库时PdfImage构造函数编译错误,求正确插入PNG图片的方法

使用PoDoFo库时PdfImage构造函数编译错误,求正确插入PNG图片的方法

嗨,我来帮你搞定这个编译错误~

你遇到的问题很明确:代码里PdfImage image(&document);这一行的参数类型不对,PoDoFo的PdfImage构造函数根本不接受PdfMemDocument*作为输入。从报错信息里能看到,它只支持两种构造方式:拷贝构造,或者传入一个PdfObject&对象。

那正确插入PNG图片的步骤应该是这样的:

  • 先给文档创建一个空的PdfObject,用来存储图片的相关数据
  • 用这个PdfObject初始化PdfImage实例
  • 调用Load方法加载PNG文件
  • 最后用PdfPainter绘制图片

下面是修正后的完整代码,我把关键部分标出来了:

#include <iostream>
#include <podofo/podofo.h>

using namespace std;
using namespace PoDoFo;

void PrintLogo(const string_view& filename) {
    PdfMemDocument document;
    PdfPainter painter;
    PdfFont* font;

    string imageFile = "C:\\image.png";

    try {
        auto& page = document.GetPages().CreatePage(PdfPage::CreateStandardPageSize(PdfPageSize::A4));
        painter.SetCanvas(page);

        font = document.GetFonts().SearchFont("Arial");
        if (!font) throw runtime_error("Invalid handle");

        painter.TextState.SetFont(*font, 18);
        painter.GraphicsState.SetFillColor(PdfColor(1, 0.5, 0.5));
        painter.GraphicsState.SetStrokeColor(PdfColor(1, 0.0, 0.0));

        // 修正的部分开始
        auto* imageObj = document.CreateObject(); // 为图片创建关联文档的PdfObject
        PdfImage image(*imageObj);
        image.Load(imageFile); // 加载PNG文件
        // 绘制图片,PDF坐标系以左下角为原点,这里把图片放在页面左下角上方70单位的位置
        painter.DrawImage(70.0, 70.0, &image);
        // 修正的部分结束
       
        painter.FinishDrawing();

        document.Save(filename);
    }

    catch (PdfError& e) {
        try {
            painter.FinishDrawing();
        }
        catch (...) {
      
        }
        throw e;
    }
}

int main() {
    try {
        const string pdfFilename = "C:\\TestPoDoFo001.pdf";

        PrintLogo(pdfFilename);
    }
    catch (PdfError& err) {
        err.PrintErrorMsg();
        return static_cast<int>(err.GetCode());
    }

    cout << endl << "Created a PDF file: TestPoDoFo001.pdf" << endl << endl;

    return 0;
}

另外还要注意几个小细节:

  • 确保你的PNG文件路径是正确的,避免因为路径问题加载失败
  • PoDoFo对PNG的支持依赖libpng库,如果你是用vcpkg安装的PoDoFo,应该已经自动处理了依赖;如果是手动编译的话,要确认已经正确链接libpng
  • DrawImage的y坐标:PDF的坐标系以左下角为原点,如果你想把图片放在页面上方,可以用page.GetRect().Height() - image.GetHeight() - 偏移量来计算具体位置,你可以根据需求调整代码里的坐标值。

备注:内容来源于stack exchange,提问作者Renzo Fabián

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 12:14:35