Cum să protejezi documentele PDF împotriva copierii și printării: tehnici de watermark și securizare

Примеры PowerShell команд
  
   import fitz  # PyMuPDF
from PIL import Image, ImageDraw, ImageFont
import datetime

# Setări generale
input_pdf = "document2.pdf"
output_pdf = "document_fara_print.pdf"
watermark_text = "TEXT"
font_size_ratio = 0.01       # proporție din lățimea paginii
text_color = (255, 0, 0, 40) # roșu opac (maxim de protecție)

# Deschidem PDF-ul
pdf = fitz.open(input_pdf)
images = []

for page_num in range(len(pdf)):
    # Convertim pagina în imagine (300 dpi)
    pix = pdf[page_num].get_pixmap(dpi=300)
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples).convert("RGBA")

    # Pregătim fontul
    font_size = int(img.width * font_size_ratio)
    try:
        font = ImageFont.truetype("arial.ttf", font_size)
    except:
        font = ImageFont.load_default()

    # Layer transparent pentru watermark
    watermark_layer = Image.new("RGBA", img.size, (0, 0, 0, 0))
    draw_wm = ImageDraw.Draw(watermark_layer)

    # Dimensiune text
    bbox = draw_wm.textbbox((0, 0), watermark_text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    # Pas între repetiții
    step_x = text_width + 200
    step_y = text_height + 200

    # Desen watermark repetat
    for y in range(-img.height, img.height * 2, step_y):
        for x in range(-img.width, img.width * 2, step_x):
            draw_wm.text((x, y), watermark_text, font=font, fill=text_color)

    # Rotim layer-ul
    rotated = watermark_layer.rotate(-45, expand=1)

    # Decupăm la dimensiunea originală
    x_center = rotated.width // 2
    y_center = rotated.height // 2
    half_w = img.width // 4
    half_h = img.height // 4
    cropped = rotated.crop((x_center - half_w, y_center - half_h,
                            x_center + half_w, y_center + half_h))

    # Asigurăm același mode și dimensiune
    cropped = cropped.convert("RGBA").resize(img.size)

    # Combinăm cu pagina originală
    watermarked = Image.alpha_composite(img, cropped)
    images.append(watermarked.convert("RGB"))

# Salvăm PDF final cu metadate
images[0].save(output_pdf, save_all=True, append_images=images[1:])

# Redeschidem pentru a adăuga metadatele
doc = fitz.open(output_pdf)
doc.set_metadata({
    "title": "Raport oficial",
    "author": "Nume Prenume",
    "subject": "Document protejat",
    "keywords": "Protecție, watermark, confidențial",
    "creator": "Sistem intern de generare PDF",
    "producer": "Denumire",
    "creationDate": datetime.datetime.now().strftime("D:%Y%m%d%H%M%S"),
    "modDate": datetime.datetime.now().strftime("D:%Y%m%d%H%M%S")
})
doc.saveIncr()
doc.close()

print(f"PDF creat cu watermark și metadate: {output_pdf}")



    

Комментариев нет: