Skip to content

Instantly share code, notes, and snippets.

@iuriguilherme
Last active December 21, 2022 23:46
Show Gist options
  • Save iuriguilherme/108991b85229f17ce1825d8cb0fea7e0 to your computer and use it in GitHub Desktop.
Save iuriguilherme/108991b85229f17ce1825d8cb0fea7e0 to your computer and use it in GitHub Desktop.
Marca d'água em PDF
"""https://t.me/pythonbr/288981
Marca d'água em PDF
pip install pypdf2 requests reportlab"""
import io
import requests
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.colors import Color
from PyPDF2 import PdfReader, PdfWriter
def gerar_pdf_imagem(
pdf: str = "original.pdf",
imagem: str = "imagem.jpg",
pdf_url: str = "https://www.africau.edu/images/default/sample.pdf",
imagem_url: str = "https://i.ytimg.com/vi/ukVkkVlbJrw/maxresdefault.jpg",
) -> None:
"""Chupacabreia pdf de exemplo e imagem da internet"""
pdf_response: requests.Response = requests.get(pdf_url)
with open(pdf, 'wb') as buf:
buf.write(pdf_response.content)
imagem_response: requests.Response = requests.get(imagem_url)
with open(imagem, 'wb') as buf:
buf.write(imagem_response.content)
def marcadagua(
texto: str = "PEDREIROS DA PUTA QUE PARIU",
entrada: str = "original.pdf",
imagem: str = "imagem.jpg",
saída: str = "out.pdf",
) -> None:
"""Sobrepõe páginas de entrada com sobreposição, grava em saída"""
reader: PdfReader = PdfReader(entrada)
writer: PdfReader = PdfWriter()
## Usa tamanho da primeira página de original.pdf para o Canvas
page: PageObject = reader.pages[0]
with io.BytesIO() as buf:
canvas = Canvas(buf, pagesize = (page.mediabox.getWidth(),
page.mediabox.getHeight()))
canvas.setFont("Helvetica", 42)
canvas.setFillColor(Color(0.1, 0.1, 0.1, alpha = 0.1))
canvas.rotate(54)
canvas.drawString(
float(page.mediabox.getWidth()) / 4.5,
float(page.mediabox.getHeight()) / 54,
texto,
)
canvas.showPage()
canvas.drawImage(imagem, 15, 15, width = 32, height = 24)
canvas.save()
buf.seek(0)
marcadágua = PdfReader(buf)
página = marcadágua.pages[0]
for page_ in reader.pages:
page_.merge_page(marcadágua.pages[0]) # texto
page_.merge_page(marcadágua.pages[1]) # imagem
writer.add_page(page_)
with open(saída, 'wb') as file_:
writer.write(file_)
if __name__ == '__main__':
gerar_pdf_imagem()
marcadagua()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment