简体   繁体   English

在pisa html到pdf库中使用link_callback的图像URL

[英]Using an image URL for link_callback in the pisa html to pdf library

Related to: django - pisa : adding images to PDF output 相关: django - pisa:将图像添加到PDF输出

I've got a site that uses the Google Chart API to display a bunch of reports to the user, and I'm trying to implement a PDF version. 我有一个网站使用Google Chart API向用户显示一堆报告,我正在尝试实现PDF版本。 I'm using the link_callback parameter in pisa.pisaDocument which works great for local media (css/images), but I'm wondering if it would work with remote images (using a google charts URL). 我使用的是link_callback参数pisa.pisaDocument伟大的工程的当地媒体(CSS /图片),但我不知道它是否会与远程图像(使用谷歌图表URL)工作。

From the documentation on the pisa website, they imply this is possible, but they don't show how: 从比萨网站上的文档中 ,他们暗示这是可能的,但他们没有说明如何:

Normaly pisa expects these files to be found on the local drive. Normaly pisa希望在本地驱动器上找到这些文件。 They may also be referenced relative to the original document. 它们也可以相对于原始文档引用。 But the programmer might want to load form different kind of sources like the Internet via HTTP requests or from a database or anything else. 但程序员可能希望通过HTTP请求或从数据库或其他任何东西加载不同类型的源,如Internet

This is in a Django project, but that's pretty irrelevant. 这是一个Django项目,但这是无关紧要的。 Here's what I'm using for rendering: 这是我用于渲染的内容:

html = render_to_string('reporting/pdf.html', keys,
                        context_instance=RequestContext(request))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(
        StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')),
        result, link_callback=link_callback)
return HttpResponse(result.getvalue(), mimetype='application/pdf')

I tried having the link_callback return a urllib request object, but it does not seem to work: 我尝试让link_callback返回一个urllib请求对象,但它似乎不起作用:

def link_callback(uri, rel):
    if uri.find('chxt') != -1:
        url = "%s?%s" % (settings.GOOGLE_CHART_URL, uri)
        return urllib2.urlopen(url)
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

The PDF it generates comes out perfectly except that the google charts images are not there. 它生成的PDF完全出来,除了谷歌图表不存在。

Well this was a whole lot easier than I expected. 那么这比我预想的要容易得多。 In your link_callback method, if the uri is a remote image, simply return that value. link_callback方法中,如果uri是远程图像,只需返回该值即可。

def link_callback(uri, rel):
    if uri.find('chart.apis.google.com') != -1:
        return uri
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

The browser is a lot less picky about the image URL, so make sure the uri is properly quoted for pisa. 对于图像URL,浏览器不那么挑剔,因此请确保为比萨正确引用uri。 I had space characters in mine which is why it was failing at first (replacing w/ '+' fixed it). 我有空间角色,这就是为什么它最初失败的原因(替换w /'+'固定它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM