如何用Python和GTK3+将PDF渲染为Pixbuf

2 投票
2 回答
1209 浏览
提问于 2025-04-17 13:58

我想把PDF文件的页面显示在GtkIconView里。为了做到这一点,我需要在我的GtkTreeModel中有一个类型为GDK_TYPE_PIXBUF的列。我该如何把PDF页面渲染成Pixbuf呢?

我有一个page,它是一个PopplerPage,我尝试了以下代码:

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 320, 240)
page.render(surface)
img = Gdk.pixbuf_get_from_surface(surface, 0, 0, 320, 240)

但是,当我执行render命令时,出现了一个关于断言的错误,内容是((*&(&cr->ref_count)->ref_count) > 0)

2 个回答

0

试试这个

 # get pdf
 pdf = mkpdf(ds,sample=True)

# render pdf onto pixbuf
pixbuf = Pixbuf(COLORSPACE_RGB,False,8,286,225)
doc = poppler.document_new_from_data(pdf,len(pdf),password='')
page0=doc.get_page(0)
page0.render_to_pixbuf(0,0,8,11,1,0,pixbuf)

# save pixbuf as png
# There has to be a better way to get the image?
lst=[]
pixbuf.save_to_callback(lambda b,l: l.append(b), 'png', user_data=lst)
png=''.join(lst)

return png

参考链接

2

最后,我搞明白了。我需要把内容渲染到一个cairo上下文中,像这样:

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context(surface)
page.render(ctx)
img = Gdk.pixbuf_get_from_surface(ctx.get_target(), 0, 0,
        ctx.get_target().get_width(),
        ctx.get_target().get_height())

撰写回答