在现有的PDF文件的每一页中插入二维码。

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

insert Qrcode in to existing Pdf file every page

问题

我试图将QR码插入PDF文件的每一页。最初,'output.pdf'文件有三页,但当我运行下面的代码时,QR码成功插入PDF文件中。然而,许多页面丢失,结果的'output.pdf'文件变成了单页。我该如何解决这个问题?以下是我正在使用的代码:

import qrcode
from reportlab.pdfgen import canvas
from PyPDF2 import PdfReader, PdfWriter

def generate_qr(data):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill='black', back_color='white')
    return img

# 生成QR码
qr_img = generate_qr('https://www.example.com')
qr_image_path = "qr_temp.png"
qr_img.save(qr_image_path)

# 从图像创建水印
c = canvas.Canvas('watermark.pdf')
c.drawImage(qr_image_path, 15, 720, width=120, height=120)  # 在此处添加您所需的位置
c.save()

# 获取刚刚创建的水印文件
watermark = PdfReader('watermark.pdf')

# 准备好我们的文件
output = PdfWriter()
input_pdf = PdfReader('input.pdf')

# 遍历所有输入文件的页面以添加水印
for page_number in range(len(input_pdf.pages)):
    print(f"正在给第 {page_number + 1} 页添加水印,共 {len(input_pdf.pages)} 页")
    page = input_pdf.pages[page_number]
    watermark_page = watermark.pages[0]
    watermark_page.mediabox = page.mediabox  # 使水印页面的大小与原始页面相同
    page.merge_page(watermark_page)
    output.add_page(page)

# 最后,将输出写入文件
with open("output.pdf", "wb") as outputStream:
    output.write(outputStream)

# 清理临时文件
import os
os.remove(qr_image_path)
os.remove('watermark.pdf')

希望这可以帮助您解决问题。如果您有其他问题,请随时提出。

英文:

I'm trying to insert a QR code into every page of a PDF file. Initially, the 'output.pdf' file has three pages, but when I run the code below, the QR code is inserted successfully into the PDF file. However, many pages are missing, and the resulting 'output.pdf' file becomes a single page. How can I fix this issue? Below is the code I am using

from reportlab.pdfgen import canvas
from PyPDF2 import PdfReader, PdfWriter

def generate_qr(data):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill='black', back_color='white')
    return img

# Generate QR code
qr_img = generate_qr('https://www.example.com')
qr_image_path = "qr_temp.png"
qr_img.save(qr_image_path)

# Create the watermark from an image
c = canvas.Canvas('watermark.pdf')
c.drawImage(qr_image_path, 15, 720, width=120, height=120)  # add your desired position here
c.save()

# Get the watermark file you just created
watermark = PdfReader('watermark.pdf')

# Get our files ready
output = PdfWriter()
input_pdf = PdfReader('input.pdf')

# Go through all the input file pages to add a watermark to them
for page_number in range(len(input_pdf.pages)):
    print(f"Watermarking page {page_number} of {len(input_pdf.pages)}")
    page = input_pdf.pages[page_number]
    watermark_page = watermark.pages[0]
    watermark_page.mediabox = page.mediabox  # to make the size of watermark page same as original page
    page.merge_page(watermark_page)
    output.add_page(page)

# Finally, write the output to a file
with open("output.pdf", "wb") as outputStream:
    output.write(outputStream)

# Clean up temporary files
import os
os.remove(qr_image_path)
os.remove('watermark.pdf') ``` 

</details>


# 答案1
**得分**: 0

这是使用PyMuPDF的方法:

```python
import qrcode
import io
import fitz  # PyMuPDF

fitz.TOOLS.set_aa_level(0)  # 将抗锯齿级别设置为0

def make_qrcode():
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data("Some data")
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    fp = io.BytesIO()
    img.save(fp, "PNG")
    return fp


rect = fitz.Rect(15, 15, 135, 135)  # 左上角的正方形,边长为120点
stream = make_qrcode()  # 内存中的QR码作为PNG图像

doc = fitz.open("input.pdf")

for page in doc:
    page.insert_image(rect, stream=stream)

doc.save("output.pdf", deflate=True, garbage=3)
英文:

This is how you would do it with PyMuPDF:

import qrcode
import io
import fitz  # PyMuPDF

fitz.TOOLS.set_aa_level(0)  # set anti-aiasing level to 0

def make_qrcode():
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(&quot;Some data&quot;)
    qr.make(fit=True)

    img = qr.make_image(fill_color=&quot;black&quot;, back_color=&quot;white&quot;)
    fp = io.BytesIO()
    img.save(fp, &quot;PNG&quot;)
    return fp


rect = fitz.Rect(15, 15, 135, 135)  # top left square, 120 points edge len
stream = make_qrcode()  # QR code as PNG image in memory

doc = fitz.open(&quot;input.pdf&quot;)

for page in doc:
    page.insert_image(rect, stream=stream)

doc.save(&quot;output.pdf&quot;, deflate=True, garbage=3)


</details>



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

发表评论

匿名网友

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

确定