如何在浏览器中打开生成的PDF文件?

发布于 2024-09-24 03:08:09 字数 1195 浏览 0 评论 0原文

我编写了一个 Pdf 合并器,它将原始文件与水印合并。

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

那么,在 Django 视图中我该怎么做呢?

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()

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

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.

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

掩耳倾听 2024-10-01 03:08:09

我知道这是一篇较旧的文章,但我们可以使用 html 的嵌入标签来实现这种功能。例如:

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

因此,在您的情况下,您可以简单地使用 render to response as: 发送响应,

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

并且在 abc.html 中,您可以将此文件名(带有路径)放在嵌入标记中,如上所述。

希望这有帮助。

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">

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

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

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

Hope this helps.

那些过往 2024-10-01 03:08:09

除了将 PDF 发送回浏览器之外,您还可以通过将水印存储在字符串缓冲区中来节省一些周期。

from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from django.http import HttpResponse
try:
   from cStringIO import StringIO
except ImportError:
   from StringIO import StringIO

def some_view(request):
   output = PdfFileWriter()
   input = PdfFileReader(file('file.pdf', 'rb'))

   #create response object
   response = HttpResponse(mimetype='application/pdf')
   response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

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

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

   # generate watermark on the fly
   buffer = StringIO() # create string buffer for PDF
   pdf = Canvas(buffer)
   pdf.setFont("chinese_font", 12)
   pdf.setStrokeColorRGB(0.5, 1, 0)
   pdf.drawString(96, 26, "88888")
   pdf.save()

   # put on watermark from buffer
   watermark = PdfFileReader(buffer)
   page1 = input.getPage(0)

   page1.mergePage(watermark.getPage(0))

   # add processed pdf page
   output.addPage(page1)


   #stream to browser
   outputStream = response
   output.write(response)
   outputStream.close()

return response

In addition to sending your PDF back to the browser, you can also save some cycles by storing your watermark in a string buffer.

from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from django.http import HttpResponse
try:
   from cStringIO import StringIO
except ImportError:
   from StringIO import StringIO

def some_view(request):
   output = PdfFileWriter()
   input = PdfFileReader(file('file.pdf', 'rb'))

   #create response object
   response = HttpResponse(mimetype='application/pdf')
   response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

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

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

   # generate watermark on the fly
   buffer = StringIO() # create string buffer for PDF
   pdf = Canvas(buffer)
   pdf.setFont("chinese_font", 12)
   pdf.setStrokeColorRGB(0.5, 1, 0)
   pdf.drawString(96, 26, "88888")
   pdf.save()

   # put on watermark from buffer
   watermark = PdfFileReader(buffer)
   page1 = input.getPage(0)

   page1.mergePage(watermark.getPage(0))

   # add processed pdf page
   output.addPage(page1)


   #stream to browser
   outputStream = response
   output.write(response)
   outputStream.close()

return response
﹂绝世的画 2024-10-01 03:08:09

我不确定我是否遵循。如果您希望将 PDF 内容发送到浏览器,您应该使用 HttpResponse 实例。代码中的这一行

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

不会用于将 PDF 内容写入响应。相反,在我看来,它将内容写入本地文件,这是不一样的。

更新

基于评论:

如何将 PDF 内容发送到 HttpResponse 对象,因为它将在浏览器中打开,而不是作为附件。

AFAIK(如果有人更了解,请纠正我)这是依赖于浏览器的。

如果您在响应标头中省略 Content-Disposition = "attachment; filename=foo.pdf ,您可以将内容发送到浏览器而不需要特定的文件名。这会提示我的 Firefox 浏览器 (3.6.10 ,Ubuntu Jaunty)询问我是否想使用程序打开它。在 Chrome(6.0.472.62,Ubuntu Jaunty)上,文件被下载为 download.pdf ,没有任何提示。

I am not sure I follow. If you want the PDF content to be sent to the browser you should use an HttpResponse instance. This line in your code

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

will not serve to write the PDF contents to the response. Instead it looks to me like it will write the contents to a local file, which is not the same.

Update

Based on comment:

How to send PDF content to a HttpResponse object as it will open in the browser, not as an attachment.

AFAIK (if anyone knows better, correct me) this is browser dependent.

If you leave out the Content-Disposition = "attachment; filename=foo.pdf from the response headers you can send the contents to the browser without a specific filename. This prompted my Firefox browser (3.6.10, Ubuntu Jaunty) to ask me if I wanted to open it using a program. On Chrome (6.0.472.62, Ubuntu Jaunty) the file got downloaded as download.pdf without any prompting.

最美的太阳 2024-10-01 03:08:09

用克里斯评论从这一行删除“附件”

response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

remove 'attachment' from this line with Chris comment

response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文