在PDF底部添加页码。

huangapple go评论74阅读模式
英文:

Add page number in the footer of pdf

问题

我需要将页码添加到PDF的页脚。已经尝试过使用pypdf和reportlab,但不知道如何实现。

  1. 从数据库生成报表数据给reportlab使用。
  2. 使用reportlab创建表格。
  3. 使用PyPDF2迭代页面并添加注释。
  4. 将文件从服务器返回给客户端。

文件生成和客户端检索部分已经正常工作。缺少的部分是添加“第x页共y页”的功能。

def create_sample_source_report_pdf(task_id):
...... 数据生成 ..........

  # 创建一个字节流以保存PDF内容
  pdf_byte_stream = io.BytesIO()
  
  # 创建PDF文档
  doc = SimpleDocTemplate(pdf_byte_stream, pagesize=landscape(A4))

  # 使用数据创建表格
  table = Table(data)
  
  # 为表格添加样式
  style = TableStyle([
      ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),  # 表头文本颜色
      ('BACKGROUND', (0, 0), (-1, 0), colors.darkgrey),  # 表头背景颜色
      ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
      ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
      ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
      ('BACKGROUND', (0, 1), (-1, -1), colors.lightgrey),  # 每第二行的浅灰色背景
      ('GRID', (0, 0), (-1, -1), 1, colors.black),
  ])
  
  table.setStyle(style)

  # 构建PDF
  doc.build([table])  # 标题的间距

  # 将指针移动到字节流的开头
  pdf_byte_stream.seek(0)

  ##################添加“第x页共y页”的文本


  # 现在,您可以使用修改后的字节流创建BlobMedia
  blob_media_pdf = BlobMedia("application/pdf", modified_pdf_byte_stream.read(), name="sample_source_list_with_page_numbers.pdf")

  return blob_media_pdf
英文:

I need to add page number to the footer of pdf. Already tried with pypdf and reportlab. I'm out of ideas how to implement it.

  1. Generation of data for reportlab to create table from the database
  2. creation of table with reportlab
  3. Iterating pages with PyPDF2 and adding Annotations
  4. return the file from the server to the client

File generation and retrieving on client side work. What is missing is the part to add the page x of y

def create_sample_source_report_pdf(task_id):
...... data generation ..........

  # Create a byte stream to hold the PDF content
  pdf_byte_stream = io.BytesIO()
  
  # Create a PDF document
  doc = SimpleDocTemplate(pdf_byte_stream, pagesize=landscape(A4))

  # Create a table with the data
  table = Table(data)
  
  # Add style to the table
  style = TableStyle([
      ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),  # Header text color
      ('BACKGROUND', (0, 0), (-1, 0), colors.darkgrey),  # Header background color
      ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
      ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
      ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
      ('BACKGROUND', (0, 1), (-1, -1), colors.lightgrey),  # Light grey background for every 2nd row
      ('GRID', (0, 0), (-1, -1), 1, colors.black),
  ])
  
  table.setStyle(style)

  # Build the PDF
  doc.build([table])  # Spacer for title

  # Move the pointer to the beginning of the byte stream
  pdf_byte_stream.seek(0)

  ##################add text with page x of y


  # Now you can use the modified byte stream to create a BlobMedia
  blob_media_pdf = BlobMedia("application/pdf", modified_pdf_byte_stream.read(), name="sample_source_list_with_page_numbers.pdf")

  return blob_media_pdf

答案1

得分: 0

以下是您要翻译的代码部分:

from pypdf import PdfReader, PdfWriter, PdfMerger, PageObject
from reportlab.lib.pagesizes import landscape, A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfgen import canvas
from reportlab.platypus import Image
from reportlab.lib.utils import ImageReader

 # 创建一个字节流以保存PDF内容
pdf_byte_stream = io.BytesIO()

##########代替每种PDF创建#########

# 使用数据和样式创建一个表格,并重复标题行
table = Table(data, style=style, repeatRows=1)

# 生成PDF文档
doc = SimpleDocTemplate(pdf_byte_stream, pagesize=landscape(A4))
doc.build([table])

# 将指针移到字节流的开头
pdf_byte_stream.seek(0)

# 使用PyPDF2读取生成的PDF
pdf_reader = PdfReader(pdf_byte_stream)

# 创建一个PdfWriter以保存修改后的PDF
pdf_writer = PdfWriter()

for page_number, page in enumerate(pdf_reader.pages):
    # 为每页创建一个新的数据包
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=landscape(A4))
    # 第一个是x轴,第二个是y轴
    can.drawString(750, 30, f"Page: {page_number + 1} of {len(pdf_reader.pages)}")
    can.save()

    # 移到StringIO缓冲区的开头
    packet.seek(0)

    # 使用pypdf读取新的PDF
    new_pdf = PdfReader(packet)

    # 将新页与原始页合并
    page.merge_page(new_pdf.pages[0])

    # 将合并后的页添加到PdfWriter
    pdf_writer.add_page(page)

# 创建一个字节流以保存修改后的PDF内容
modified_pdf_byte_stream = io.BytesIO()

# 将修改后的PDF写入新的字节流
pdf_writer.write(modified_pdf_byte_stream)

# 移动指针到修改后字节流的开头
modified_pdf_byte_stream.seek(0)

# 现在您可以使用字节流创建一个BlobMedia
blob_media_pdf = BlobMedia("application/pdf", modified_pdf_byte_stream.read(), name="sample_source_list_with_page_numbers.pdf")

# 返回BlobMedia对象
return blob_media_pdf

希望这对您有所帮助。如果您有任何其他问题,请随时提问。

英文:

Found a way to create a new page with the text and then merge it with pypdf.

from pypdf import PdfReader, PdfWriter, PdfMerger, PageObject
from reportlab.lib.pagesizes import landscape, A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfgen import canvas
from reportlab.platypus import Image
from reportlab.lib.utils import ImageReader


 # Create a byte stream to hold the PDF content
  pdf_byte_stream = io.BytesIO()
  
  ##########instead of pdf creation every kind of pdf can be loaded#########

  # Create a table with the data and style, and repeat the header row
  table = Table(data, style=style, repeatRows=1)
  
  # Build the PDF
  doc = SimpleDocTemplate(pdf_byte_stream, pagesize=landscape(A4))
  doc.build([table])
  
  # Move the pointer to the beginning of the byte stream
  pdf_byte_stream.seek(0)
  
  # Read the generated PDF with PyPDF2
  pdf_reader = PdfReader(pdf_byte_stream)
  
  # Create a PdfWriter to hold the modified PDF
  pdf_writer = PdfWriter()
  
  for page_number, page in enumerate(pdf_reader.pages):
      # Create a new packet for each page
      packet = io.BytesIO()
      can = canvas.Canvas(packet, pagesize=landscape(A4))
      #firs is the x ax, 2nd i y
      can.drawString(750, 30, f"Page: {page_number + 1} of {len(pdf_reader.pages)}")
      can.save()
  
      # Move to the beginning of the StringIO buffer
      packet.seek(0)
  
      # Read the new PDF with pypdf
      new_pdf = PdfReader(packet)
      
      # Merge the new page with the original page
      page.merge_page(new_pdf.pages[0])
      
      # Add the merged page to the PdfWriter
      pdf_writer.add_page(page)

    
  # Create a byte stream to hold the modified PDF content
  modified_pdf_byte_stream = io.BytesIO()
  
  # Write the modified PDF to the new byte stream
  pdf_writer.write(modified_pdf_byte_stream)
  
  # Move the pointer to the beginning of the modified byte stream
  modified_pdf_byte_stream.seek(0)
  
  # Now you can use the byte stream to create a BlobMedia
  blob_media_pdf = BlobMedia("application/pdf", modified_pdf_byte_stream.read(), name="sample_source_list_with_page_numbers.pdf")
  
  # Return the BlobMedia object
  return blob_media_pdf

huangapple
  • 本文由 发表于 2023年8月10日 16:43:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定