如何在浏览器中打开生成的PDF文件? [英] How to open a generated PDF file in browser?

查看:185
本文介绍了如何在浏览器中打开生成的PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了Pdf合并程序,该合并程序将原始文件与水印合并.

I have written a Pdf merger which merges an original file with a watermark.

我现在要做的是通过Django视图在浏览器中打开"document-output.pdf"文件.我已经检查了Django的相关文章,但是由于我的方法相对不同,所以我没有直接使用响应对象作为其文件"来创建PDF对象,所以我有点迷失了.

What I want to do now is to open 'document-output.pdf' file in the browser by a Django view. I already checked Django's related articles, but since my approach is relatively different, I don't directly create the PDF object, using the response object as its "file.", so I am kind of lost.

那么,如何在Django视图中进行操作?

So, how can I do is in a Django view?

from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

output = PdfFileWriter()
input = PdfFileReader(file('file.pdf', 'rb'))

# get number of pages
num_pages = input.getNumPages()

# register new chinese font
pdfmetrics.registerFont(TTFont('chinese_font','/usr/share/fonts/truetype/mac/LiHeiPro.ttf'))

# generate watermark on the fly
pdf = Canvas("watermark.pdf")
pdf.setFont("chinese_font", 12)
pdf.setStrokeColorRGB(0.5, 1, 0)
pdf.drawString(10, 830, "你好")
pdf.save()

# put on watermark
watermark = PdfFileReader(file('watermark.pdf', 'rb'))
page1 = input.getPage(0)

page1.mergePage(watermark.getPage(0))

# add processed pdf page
output.addPage(page1)

# then, add rest of pages
for num in range(1, num_pages):
    output.addPage(input.getPage(num))

outputStream = file("document-output.pdf", "wb")
output.write(outputStream)
outputStream.close()

推荐答案

我知道它是较老的文章,但是我们可以使用html的embed标记来实现这种功能.例如:

I know its an older post but we can use the embed tag of html to implement this kind of functionality. For e.g.:

<embed height="100%" width="100%"  name="plugin" src="filename.pdf"  type="application/pdf">

因此,在您的情况下,您可以简单地使用render向响应发送响应,如下所示:

So in your case, you can simply send the response using render to response as:

return render_to_response("abc.html",{"filename":filename})

和在abc.html中,您可以将该文件名(带有路径)放在embed标签中,如上所述.

and in the abc.html you can put this filename (with the path) in the embed tag, as mentioned above.

希望这会有所帮助.

这篇关于如何在浏览器中打开生成的PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆