如何用Python和GTK3将PDF转换成Pixbuf+

2024-10-01 11:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把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)

但是,当断言((*&(&cr->ref_count)->ref_count) > 0)执行render命令时,我得到了一个错误。在


Tags: 文件ref类型pdftypecountpage页面
2条回答

试试这个

 # 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

Reference

最后,我明白了。我必须呈现一个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())

相关问题 更多 >