def build(self): if self.passwd: enc = pdfencrypt.StandardEncryption(self.passwd, canPrint=1) else: enc = None doc = SimpleDocTemplate(self.path + self.name, author='eisoo.com', title=self.title, encrypt=enc,leftMargin=40,rightMargin=40) if self.need_draw_frame: doc.build(self.data_list, onFirstPage=self.drawPageFrame, onLaterPages=self.drawPageFrame) else: doc.build(self.data_list)
def test_standardencryption(self): "Test generating an encrypted pdf by passing a StandardEncryption object to the Canvas." encrypt = pdfencrypt.StandardEncryption(userPassword='******', ownerPassword='******') encrypt.setAllPermissions(0) encrypt.canPrint = 1 fname = outputfile('test_encrypt_canvas2.pdf') c = Canvas(fname, encrypt=encrypt) c.setAuthor('Anonymous') c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Top secret') c.save() parsedoc(fname)
def testStdEnc(expectedO,expectedU,expectedKey, strength=40, overrideID='xxxxxxxxxxxxxxxx', userPass='******',ownerPass='******', ): # do a 40 bit example known to work in Acrobat Reader 4.0 enc = pdfencrypt.StandardEncryption(userPass,ownerPass, strength=strength) enc.setAllPermissions(0) enc.canPrint = 1 enc.prepare(None,overrideID) pdfencrypt.equalityCheck(pdfencrypt.hexText(enc.O),expectedO, '%d bit O value'%strength) pdfencrypt.equalityCheck(pdfencrypt.hexText(enc.U),expectedU, '%d bit U value'%strength) pdfencrypt.equalityCheck(pdfencrypt.hexText(enc.key),expectedKey, '%d bit key value'%strength)
def makedoc(fileName, userPass="******", ownerPass="******"): """ Creates a simple encrypted pdf. """ encrypt = pdfencrypt.StandardEncryption(userPass, ownerPass) encrypt.setAllPermissions(0) encrypt.canPrint = 1 c = canvas.Canvas(fileName) c._doc.encrypt = encrypt c.drawString(100, 500, "hello world") c.save()
def save(self, result: ResultRecord, file_name="", overwrite=True): layout = self(result) filename = file_name if file_name else result.doc_id + ".pdf" if os.path.exists(filename) and overwrite is False: raise Exception("file exist. not overwrite : ", filename) enc = pdfencrypt.StandardEncryption( result.password, canPrint=0) if result.password else None doc = SimpleDocTemplate(filename, pagesize=A4, encrypt=enc, title=self.doc_title) doc.build([ layout, ])
def __init__(self, fabletitle, standalone): enc = pdfencrypt.StandardEncryption('', ownerPassword="******", canCopy=0, canModify=0) self._doc = fabletemplate.FableMeDocTemplate(None, title=fabletitle, pagesize=A4, topMargin=2 * cm, bottomMargin=2 * cm, leftMargin=2 * cm, rightMargin=2 * cm, encrypt=enc) self._story = [] styler = stylesheet.PdfStyler(standalone) self._styles = styler.fableMeStyleSheet()
def encryption_demo(userPassword, ownerPassword, canPrint=1, canModify=1, canCopy=1, canAnnotate=1): encrypt = pdfencrypt.StandardEncryption(userPassword=userPassword, ownerPassword=ownerPassword, canPrint=canPrint, canModify=canModify, canCopy=canCopy, canAnnotate=canAnnotate, strength=40) my_canvas = canvas.Canvas('encryption_demo.pdf', encrypt=encrypt) my_canvas.drawString(20, 750, 'This is page one') my_canvas.save()
def test5(self,uopw=None): from reportlab.lib.pagesizes import A4,LETTER from reportlab.lib.rl_accel import fp_str if uopw: from reportlab.lib import pdfencrypt encrypt = pdfencrypt.StandardEncryption(uopw[0], uopw[1]) encrypt.setAllPermissions(0) encrypt.canPrint = 1 canv = canvas.Canvas(outputfile('test_pdfgen_general_page_sizes_encrypted.pdf'),pagesize=A4) canv._doc.encrypt = encrypt else: canv = canvas.Canvas(outputfile('test_pdfgen_general_page_sizes.pdf'),pagesize=A4) def tstr(*args): return tuple((fp_str(a) for a in args)) canv.setFont('Helvetica',10) S = A4 canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % tstr(0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % tstr(0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % tstr(S[0],0,S[0],S[1])) canv.showPage() S = LETTER canv.setPageSize(S) canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % tstr(0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % tstr(0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % tstr(S[0],0,S[0],S[1])) canv.showPage() S = A4 canv.setPageSize(S) canv.setPageRotation(180) canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % tstr(0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % tstr(0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % tstr(S[0],0,S[0],S[1])) canv.showPage() S = A4[1],A4[0] canv.setPageSize(S) canv.setPageRotation(0) canv.drawString(0,S[1]-30,'Top Left=(%s,%s) Page Size=%s x %s' % tstr(0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % tstr(0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],32,'Bottom Right=(%s,%s) Page Size=%s x %s' % tstr(S[0],0,S[0],S[1])) canv.showPage() canv.save()
def despliega_resumen_pdf(): from reportlab.lib import colors, pdfencrypt from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet filename = nombre_análisis.format( datetime(mes_final.year, mes_final.month, 1)) + '.pdf' outputfile = os.path.join(attach_path, filename) # Security of .pdf files allow_print = pdfencrypt.StandardEncryption( "", # sin contraseña canPrint=1, canModify=0, canCopy=0, canAnnotate=0, strength=128) doc = SimpleDocTemplate(outputfile, pagesize=(11 * 72, 8.5 * 72), leftMargin=36, rightMargin=36, topMargin=36, bottomMargin=18, encrypt=allow_print) FONT_NAME = 'Times-Roman' FONT_NAME_HELVETICA = 'Helvetica' styleSheet = getSampleStyleSheet() normalStyle = styleSheet['Normal'] normalStyle.fontName = FONT_NAME normalStyle.alignment = 4 # TA_JUSTIFY bodytextStyle = styleSheet['BodyText'] bodytextStyle.fontName = FONT_NAME bodytextStyle.alignment = 4 # TA_JUSTIFY # Genera la tabla de valores a desplegar num_rows, num_columns = ws_relacion_ingresos.shape columns = list(ws_relacion_ingresos.columns) # tabla = [[Paragraph(f'<para wordwrap=CJK>{col}</para>', bodytextStyle) for col in columns]] tabla = [[ Paragraph(f"<para align='CENTER'>{col}</para>", bodytextStyle) for col in columns ]] # tabla = [[columns]] for row in range(num_rows): linea = list() linea.append( f"{ws_relacion_ingresos.iloc[row]['Mes'].strftime('%b. %Y').title()}" ) for col in range(1, num_columns): monto = ws_relacion_ingresos.iloc[row][columns[col]] str_monto = '' if isnan(monto) else edita_número(monto, num_decimals=2) linea.append(str_monto) tabla.append(linea) primera_fila = ['' for _ in columns] primera_fila[1] = Paragraph(' Categorias', bodytextStyle) tabla.insert(0, primera_fila) # colwidths = [72 for _ in columns[1:]] colwidths = [80 for _ in columns[1:]] colwidths.insert(0, 60) # Crea la maqueta del archivo .PDF body = list() body.append( Paragraph( '<font size=14><b>GyG - Total de Ingresos Mensuales</b></font>', normalStyle)) período = f"{mes_inicial.strftime('%B').title()} {mes_inicial.strftime('%Y')+' ' if mes_inicial.year != mes_final.year else ''}" + \ f"a {mes_final.strftime('%B %Y').title()}" body.append(Spacer(1, 6)) body.append( Paragraph(f'<font size=10><i>{período}</i></font>', normalStyle)) body.append(Spacer(1, 24)) tabla_resumen = Table(tabla, colWidths=colwidths, hAlign='LEFT') # Table coordinates are given as (column, row) which follows the spreadsheet 'A1' model, # but not the more natural (for mathematicians) 'RC' ordering. The top left cell is (0, 0) # the bottom right is (-1, -1) tabla_resumen.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, 1), 'BOTTOM'), # todas las columnas, 1ra y 2da fila # ('TEXTCOLOR', ( 0, 0), (-1, 1), colors.white), # todas las columnas, 1ra y 2da fila ('BACKGROUND', (0, 0), (-1, 1), colors.cornflowerblue ), # todas las columnas, 1ra y 2da fila ('ALIGN', (1, 0), (1, 0), 'LEFT'), # columna 'B1': 'Categorías' ('ALIGN', (0, 1), (-1, 1), 'CENTER'), # todas las columnas, 2da fila ('LINEABOVE', (1, 1), (-2, 1), 0.25, colors.white), # desde 'B2' hasta '<end-1>2' ('LINEBEFORE', (1, 0), (1, 0), 0.25, colors.white), # antes de ' Categoría' ('LINEBEFORE', (-1, 0), (-1, 0), 0.25, colors.white), # después de la última categoría ('LINEBEFORE', (0, 1), (-1, 1), 0.25, colors.white), # entre columnas, 2da línea ('ALIGN', (0, 2), (0, -1), 'CENTER'), # todas las filas a partir de la 3ra fila ('ALIGN', (1, 2), (-1, -1), 'RIGHT'), # bloque 'B3:<end><end>' # ('VALIGN', ( 1, 1), (-1, -1), 'TOP'), # ('FONTNAME', ( 0, 0), (-1, -1), FONT_NAME_HELVETICA), # ('FONTSIZE', ( 0, 0), (-1, -1), 10) ])) body.append(tabla_resumen) body.append(Spacer(1, 24)) body.append( Paragraph( f"<font size=10><i>(resumen generado el {ahora.strftime('%d/%m/%Y %I:%M')}{am_pm})</i></font>", normalStyle)) print(f'Generando "{filename}"...') doc.build(body)
from reportlab.pdfgen import canvas from reportlab.lib import pdfencrypt enc = pdfencrypt.StandardEncryption("passcode", canPrint=0) def hello(c): c.drawString(100, 100, "How to Encrypt") c = canvas.Canvas("07_encryption.pdf", encrypt=enc) hello(c) c.showPage() c.save()
def generate_pdf(output, json_dat, qrcode=False, wifi_ssid=None, encrypt=False, layout='1', pwdelems=True, hint=True, title=None): w = [] h = [] try: for dic in json_dat: if not dic['separator']: w.append(dic['password']) h.append(dic['hint']) else: if w == []: w.append("") if h == []: h.append("") w[-1] += dic['password'] h[-1] += dic['hint'] except LookupError: raise BadDataError password = "".join(w) dat = (w, h) if wifi_ssid: qrcode = True if title == None: title = wifi_ssid if qrcode: import qrcode if wifi_ssid: qr_dat = 'WIFI:T:WPA;S:"{}";P:"{}";;'.format( wifi_quote(wifi_ssid), wifi_quote(password)) else: qr_dat = password qr = qrcode.make(qr_dat) qr = qr.get_image() qr = ImageReader(qr) else: qr = None if encrypt: enc = pdfencrypt.StandardEncryption(password + "--usr", password, strength=128) else: enc = None layout = layouts[layout] c = layout.draw(output, dat, hint=hint, pwdelems=pwdelems, qr=qr, title=title, pdfargs={'encrypt': enc}) c.setCreator(FULL_VERSION) c.setAuthor('') c.setSubject('') c.setTitle(title or '') c.showPage() c.save()