Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #DO ZROBIENIA - PRZYPADEK DLA PDF Z KILKOMA STRONAMI ZARÓWNO DLA FILL JAK I WATERMARK
- from datetime import datetime
- from pathlib import Path
- import PyPDF2
- import docx
- from python_docx_replace import docx_replace
- from reportlab.pdfgen import canvas
- from reportlab.lib.pagesizes import A4
- from reportlab.lib.units import mm, cm
- from reportlab.lib.styles import getSampleStyleSheet
- from reportlab.platypus import Paragraph, Frame
- import os
- today_date = datetime.now().strftime("%d.%m.%Y")
- TEMPLATE_FILES_DIR = Path.cwd() / 'templates'
- OUTPUT_DIR = Path.cwd() / 'output'
- INPUT_PROMPT = "Podaj w postaci cyfry do kogo chesz wygenerować wniosek np 1 lub wpisz lista jeżeli " \
- "nie wiesz jaka cyfra odpowiada wnioskowi lub exit jeżeli chcesz wyjśc z programu: "
- TEMPLATES = {
- "1": {
- "help_name": "Zarząd Drogowy w Pcimiu",
- "file_name": "PR do ZD w Pcimiu - Wniosek o uzgodnienie lokalizacji sieci i przyłącza gazowego",
- "docx_template_name": "ZDwOlkusz_template.docx",
- "replacements": {
- "today_date": today_date,
- "connection_plural_or_singular_uppercase": "PRZYŁĄCZY I", #PRZYŁĄCZY I, PRZYŁĄCZA I, "BLANK"
- "title": "xxxxx",
- "road_plots": "567/8",
- "city": "krakow",
- "street": "ul. Gałgana",
- "connection_plural_or_singular_lowercase": "przyłącza i"
- }
- },
- "2": {
- "help_name": "Przedsiębiorstwo Wodociagów i Kanalizacji Sp. z o.o. w Pcimiu",
- "file_name": "PR do PWiK w Pcimiu - Wniosek o uzgodnienie branżowe",
- "docx_template_name": "PWiKOlkusz_template.docx",
- "replacements": {
- "today_date": today_date,
- "title": "xxxxxxxx",
- }
- },
- "3": {
- "help_name": "TAURON Dystrybucja S.A Katowice",
- "file_name": "PR do Tauron - Wniosek o uzgodnienie branżowe",
- "pdf_template_name": "TauronKatowice_template.pdf",
- "pdf_needed_pages_number": "0", #ilość stron z których składa się wniosek (do wydruku) #narazie nie używane
- "replacements": {
- "TextField27[2]": "xxxxx",
- "TextField28[4]": " ", #dzialki
- "TextField27[3]": "xxxx", #gmina
- "TextField28[6]": "xx",
- "TextField27[4]": "xx", #miejscowość
- "TextField28[5]": "xxxxx",
- "plots": "567/8",
- "today_date": today_date
- }
- }
- }
- def create_docx_from_template(template: Path, output_dir: Path, replacements: dict[str, str]) -> Path:
- date = datetime.now().strftime("%Y-%m-%d")
- doc = docx.Document(template)
- docx_replace(doc, **replacements)
- output_path = output_dir / f"{date} {TEMPLATES[choice]['file_name']}.docx" #template.name ucina nazwę pliku ze blabla/costam.pdf = costam.pdf ścieżki (podaje ostatni człon z rozszerzeniem)
- doc.save(output_path)
- return output_path
- def _print_help() -> None:
- for idx, data in TEMPLATES.items():
- print(f"{idx} - {data['help_name']}")
- def _generate_docx(choice: str) -> None:
- template_path = TEMPLATE_FILES_DIR / TEMPLATES[choice]["docx_template_name"]
- replacements = TEMPLATES[choice]["replacements"]
- output_path = create_docx_from_template(template_path, OUTPUT_DIR, replacements)
- print(f"Wniosek został wygenerowany: {output_path}")
- def fill_and_generate_pdf(choice: str) -> Path:
- #część do wypełniania gotowych pół w pdf plik help1
- date = datetime.now().strftime("%Y-%m-%d")
- template_path = TEMPLATE_FILES_DIR / TEMPLATES[choice]["pdf_template_name"]
- reader = PyPDF2.PdfReader(template_path)
- writer = PyPDF2.PdfWriter()
- page = reader.pages[0]
- #fields = reader.get_form_text_fields()
- writer.add_page(page)
- writer.update_page_form_field_values(writer.pages[0], TEMPLATES[choice]["replacements"])
- output_path = OUTPUT_DIR / f"{date}_help1_{TEMPLATES[choice]['file_name']}.pdf"
- with open(output_path, "wb") as filled_out_pdf:
- writer.write(filled_out_pdf)
- print("sciezka pierwszego wygenerowanego pliku", output_path)
- return output_path
- #efekt końcowy to plik pdf o nazwie w środku help1
- #część do rysowania nowych pół pdf plik help2
- def tauron(choice: str) -> Path:
- date = datetime.now().strftime("%Y-%m-%d")
- UNIT = mm
- #output_temporary_path = OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf"
- #print(output_temporary_path) #C:\Users\Administrator\Pulpit\Programowanie\Python\kod\example\output\2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branżowe.pdf
- #c = canvas.Canvas("output_temporary_path", pagesize=A4)
- c = canvas.Canvas("output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf", pagesize=A4)
- #c = canvas.Canvas(OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf", pagesize=A4)
- output_path = OUTPUT_DIR / f"{date}_help2_{TEMPLATES[choice]['file_name']}.pdf"
- width, height = A4
- styleSheet = getSampleStyleSheet()
- style = styleSheet['BodyText']
- def making_fields(x_field_coord: int, y_field_coord: int, field_width: int, field_height: int) -> int:
- result_list = [n*UNIT for n in (x_field_coord, y_field_coord, field_width, field_height)]
- return result_list
- text = "dupa" #TEMPLATES[choice]['replacements'][plots]
- plots = []
- plots.append(Paragraph(text, style))
- text2 = "dupa2" #f"Przeginia, {TEMPLATES[choice]['replacements'][today_date]}"
- city_and_today_date = []
- city_and_today_date.append(Paragraph(text2, style))
- f_plots = Frame(*making_fields(158, 156, 43, 15), leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, id=None, showBoundary=0)
- f_city_date = Frame(*making_fields(8, 31, 95, 11), leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, id=None, showBoundary=0)
- f_plots.addFromList(plots, c)
- f_city_date.addFromList(city_and_today_date, c)
- c.showPage()
- c.save()
- print("sciezka drugiego wygenerowanego pliku", output_path)
- return output_path
- #tu sie kończy tworzenie pliku help2
- def merge_fields_with_template(template_file, fields_template):
- date = datetime.now().strftime("%Y-%m-%d")
- output_path = OUTPUT_DIR / f"{date} {TEMPLATES[choice]['file_name']}.pdf"
- # Open the template PDF and fields files in read-binary mode
- with open(template_file, 'rb') as file:
- pdf = PyPDF2.PdfReader(file)
- # Open the fields PDF in read-binary mode
- with open(fields_template, 'rb') as fields:
- fields_pdf = PyPDF2.PdfReader(fields)
- # Get the first page of the template PDF
- page = pdf.pages[0]
- # Merge the fields PDF with the template PDF page as an overlay
- page.merge_page(fields_pdf.pages[0])
- # Create a new PDF writer object
- writer = PyPDF2.PdfWriter()
- # Add the modified page to the writer
- writer.add_page(page)
- # Write the modified PDF to the output file
- with open(output_path, 'wb') as output:
- writer.write(output)
- # Provide the template PDF file, fields PDF file, and the output file name
- print(f"Wniosek został wygenerowany: {output_path}")
- return output_path
- if __name__ == "__main__":
- while (choice := input(INPUT_PROMPT)) != "exit":
- if choice == "lista":
- _print_help()
- elif choice == "3":
- merge_fields_with_template(fill_and_generate_pdf(choice), tauron(choice))
- #merge_fields_with_template(fill_and_generate_pdf(choice), "output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf")
- #merge_fields_with_template("output/2023-06-09_help1_PR do Tauron - Wniosek o uzgodnienie branżowe.pdf", "output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf") # output/2023-06-09_help2_PR do Tauron - Wniosek o uzgodnienie branzowe.pdf
- elif choice in TEMPLATES.keys():
- _generate_docx(choice)
- else:
- print(f"Nieznana komenda!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement